Skip to main content

Integrate an HTTP API

Squid offers the capability to integrate an API with your project, allowing you to harness the power of Squid with multiple data sources without worrying about a complex migration.

TL;DR

In this tutorial you will learn how to connect an external HTTP API to your Squid project. This includes:

This tutorial uses React and Squid to connect to a sample Cat Facts API and display a random fact about cats. A basic understanding of React and the Squid platform is beneficial, but there are no prerequisites for this guide.

To view a completed version of the app, check out the Squid Cloud samples on GitHub.

To view a completed version of the app, check out the Squid Cloud samples on GitHub.

Create a new React project

First, create a new directory that will contain all the files for this project.

mkdir api

Next, cd into the root directory and create a new React typescript application using Vite. This will be the frontend of the project.

npm create vite@latest api-frontend -- --template react-ts

Next, cd into the newly created directory and install all dependencies

cd api-frontend
npm install

Create a new app in the console

Navigate to the Squid Console and create a new application named api.

Note

Squid provides two different target environments for development and production. Use the dev environment for this tutorial, but note that prod is an option as well. For the application to work, ensure that you are using the same target environment throughout the project. To learn more, read about Squid's environments.

Follow the steps in the console to generate a backend template project. To view these steps, click the Initialize backend and Create .env file on the overview page. Make sure to cd back into the root project directory before initializing the backend so that the frontend and backend directories are siblings.

Create an API integration

In the console, navigate to the application's Integrations page and add a new API integration. Note that integrations are not shared across environments, so make sure you are using the correct environment (likely dev for development purposes).

API Tutorial 1

Next, enter values in the two input fields, Integration ID and OpenAPI specification URL:

  • For the ID, choose something meaningful which represents what this integration represents, such as catFacts
  • The OpenAPI specification provides a standardized way to document APIs. The URL is provided by the API and can be found on the API's home page: https://catfact.ninja/docs/api-docs.json

Providing this URL establishes Squid's connection to the API. Click the Next button to see Squid automatically discover the API Schema. Whenever a change is made to the API, you can manually Rediscover schema as well (though this will not be needed in this tutorial).

  • To finalize the connection to the Cat Facts API, edit the Base URL in the top left of the integration screen. The base URL provides the initial path for all available endpoints in this API. The URL can be found in the API's home page by executing a sample query. For the Cat Facts API, the URL is https://catfact.ninja.

Once you have completed this step, click Add integration to add it to your project!

Understanding the integration

Now that we have added the API integration, we can begin to understand more about how to use the integration. The integration's Schema page lists all the endpoints Squid automatically discovered.

As an example, click on the getRandomFact endpoint.

API Tutorial 2

This view provides all the information you need to utilize each endpoint:

  • URL: describes the path for using this endpoint.
  • Request: provides a list of options that are required for this endpoint. For getRandomFact, you must specify the max_length of the fact.
  • Injections: inject additional fields to all requests for that endpoint, either in the header or body. This can be used to store secret values, such as an API Key. Because the Cat Facts API does not require an API Key, we do not need to add an injection.
  • Response: describes what a response looks like after consuming this endpoint. For getRandomFact, the response contains two fields – the cat fact, and the length of the fact.

With this information we are now ready to use the integration in our project.

Security rules

Security rules are required for all external API integrations. This allows you to create custom logic for authorizing access to integrations and specific endpoints. Since authentication and authorization are outside the scope of this tutorial, we create a security rule which allows for all access to the catFacts integration.

Tip

To learn more about securing your data, read about Squid's backend security rules.

Security rules are located in the file api-backend/src/service/example-service.ts. The security rules can be expanded by adding a decorator to the SquidService class. To create a security rule for an API integration, use the @secureApi decorator, which takes the integration_id as a parameter. Create a new security rule in the ExampleService class:

Backend code
import { secureApi, secureDatabase, SquidService } from '@squidcloud/backend';
import { ApiCallContext } from "@squidcloud/client";

...

export class ExampleService extends SquidService {

...

@secureApi('catFacts')
secureCatFacts(context: ApiCallContext): boolean {
return true; // Allows all access to the catFacts integration
}
}

Use the API on the client

The last step is to use the integration in the React project using the Squid React SDK.

Setup

First, install the Squid React SDK in the api-frontend directory:

npm install @squidcloud/react

Next, in src/main.tsx, wrap the App component in the SquidContextProvider with the configuration options located in your .env file. The .env file was automatically generated while creating the app in the console.

Client code
import { SquidContextProvider } from '@squidcloud/react';


...

ReactDOM.createRoot(document.getElementById('root')!).render(
<SquidContextProvider
options={{
appId: 'YOUR_APP_ID',
region: 'YOUR_REGION', // example: 'us-east-1.aws'
environmentId: 'dev | prod', // choose one of 'dev' or 'prod'
squidDeveloperId: 'YOUR_SQUID_DEVELOPER_ID',
}}
>
<App />
</SquidContextProvider>
);

App.tsx

Next, we edit src/App.tsx to utilize the new integration.

We can use the squid.api().request() method in the Squid React SDK to use an endpoint in the API integration. The request() method takes three parameters:

  • integrationId: we named this integration catFacts
  • endpointId: we use getRandomFact after discovering the API's schema in the console
  • body object: which we know from earlier that the request must contain a max_length

The request() method returns a promise:

Client code
squid.api().request('catFacts', 'getRandomFact', { max_length: 70 });

We can now invoke this method in our App component. First, create a React state to track the fact that the integration returns. Once we invoke the request function, we can update the state with the new fact data. Because request returns a promise, we must use the .then method to access the data once the promise is resolved. As a React trick, we will wrap the call in a useEffect hook so that it only executes once.

Client code
function App() {
const squid = useSquid();

/* The endpoint's response object has a fact and its length. This can be
* verified in the console */
const [randomFact, setFact] = useState({ fact: '', length: 0 });

useEffect(() => {
squid
.api()
.request('catFacts', 'getRandomFact', { max_length: 70 })
.then((data) => {
setFact(data.body as RandomFact);
});
}, []);
}

Finally, render the fact on the page by accessing the fact field of the catFact state. The full App.tsx example can be found below:

Client code
import { useEffect, useState } from 'react';
import { useSquid } from '@squidcloud/react';
import './App.css';

interface RandomFact {
fact: string;
length: number;
}

function App() {
const squid = useSquid();
const [randomFact, setFact] = useState({ fact: '', length: 0 });

useEffect(() => {
squid
.api()
.request('catFacts', 'getRandomFact', { max_length: 70 })
.then((data) => {
setFact(data.body as RandomFact);
});
}, []);

return (
<>
<div>
Fact: {randomFact?.fact} <br />
Length: {randomFact?.length}
</div>
</>
);
}

export default App;

Run the project

To run the project, you must start both the client React project as well as the backend Squid project.

To run the backend, run the following from the api-backend folder:

squid start

To run the client, open a second terminal window and run the following from the root folder:

npm run dev

You can now see the client project running at http://localhost:PORT, where the port is logged in the terminal. The page displays the fact and its length in characters. To view a new random cat fact, refresh the page.

Congratulations! You have officially setup your first API integration with Squid in just a matter of minutes!

Next steps

To learn more about the capabilities of Squid API integrations, view the Client SDK documentation on calling an API. To find out how to customize security for your HTTP API endpoint, view the Backend SDK documentation.