How to integrate multiple REST APIs

Learn how to effectively integrate multiple REST APIs, as well as how to do it in Hygraph with the help of remote sources.

GraphCMS Favicon
Hygraph Team
integrating rest apis

The ability to connect and integrate different systems and platforms is crucial for businesses to function effectively in today's digital environment. One way to achieve this is through the use of REST APIs. REST, or Representational State Transfer, is an architectural style for building web services. RESTful APIs are a flexible and efficient way for different systems and applications to communicate with each other and are widely used in modern web development. This article will talk about the concept of REST APIs, their importance, and how to effectively implement them into your own systems and applications.

Components of a Rest APIAnchor

REST ArchitectureAnchor

RESTful APIs are based on the REST architecture, which is a set of principles for building web services. The principles of REST include statelessness, caching, and a uniform interface. RESTful APIs are stateless, which means that the server does not store any information about the client. Additionally, RESTful APIs can be cached, meaning the server can store a copy of a resource so that it does not have to be requested again.

REST MethodsAnchor

RESTful APIs use a set of standard methods to access and manipulate web resources. The most commonly used methods are GET, POST, PUT and DELETE. GET is used to retrieve a resource, POST is used to create a new resource, PUT is used to update an existing resource, and DELETE is used to delete a resource.

REST ProtocolsAnchor

RESTful APIs use HTTP (Hypertext Transfer Protocol) as the communication protocol. HTTP is the same protocol that is used by the World Wide Web and it is a standard protocol for transmitting data over the internet.

Data FormatsAnchor

RESTful APIs can return data in various formats such as XML and JSON. JSON (JavaScript Object Notation) is the most common format used in RESTful APIs as it is lightweight and easy to parse. XML (Extensible Markup Language) is also widely used but it is less popular than JSON.

EndpointsAnchor

RESTful APIs have a set of endpoints that are used to access and manipulate resources. Endpoints are URLs that define the location of a resource on the server. Each endpoint corresponds to a specific resource and uses different methods to access the resource.

API SecurityAnchor

RESTful APIs need to be secured properly to protect sensitive data. Authentication and Authorization are the two major aspects of API security. Authentication is the process of verifying the identity of a user and Authorization is the process of determining if a user has access to a specific resource.

Please refer to How do APIs work for a deep dive into the internal workings of an API

ExampleAnchor

Here is an example of how you can use the axios module in a Next.js API to make a GET request to an external REST API.

import axios from 'axios';
async function getData() {
try {
const response = await axios.get('https://api.github.com/search/repositories', {
params: {
q: 'nextjs',
sort: 'stars',
per_page: 10
}
});
console.log(response.data);
} catch (error) {
console.log(error);
}
}
getData();

Here we are searching for the repositories related to the nextjs, sorting by stars and limiting the number of results to 10. The axios.get() method takes the API endpoint as its parameter and returns a promise. If the request is successful, the promise is resolved with the response data, which is logged into the console. If there is an error, the promise is rejected and the error is logged to the console.

This is a simple example of how to make a GET request to an external REST API in Node.js, you can use similar approaches to make POST, PUT, and DELETE requests and also you can customize it by adding query parameters, headers, and request bodies as per your requirement.

Integrating Rest APIsAnchor

Use CasesAnchor

Integrating multiple REST APIs is becoming increasingly important for businesses as technology continues to advance. Connecting various systems and platforms is crucial for businesses to stay competitive and provide a seamless experience for their customers.

One of the main reasons for integrating multiple REST APIs is to access a wider range of data and functionality. For example, a retail business may want to integrate with a payment API, shipping API, and inventory API to provide a complete e-commerce solution for its customers. By integrating these different APIs, the business can access the necessary data and functionality to process payments, calculate shipping rates, and check inventory levels, all in one place.

Another reason for integrating multiple REST APIs is to improve the efficiency of a process. For example, a logistics company may need to integrate with multiple external APIs to track packages, calculate shipping rates, and check delivery status. This eliminates the need for manual data entry and improves the accuracy of the package information.

Integrating multiple REST APIs can also help to enhance the user experience. For example, a travel application may integrate with multiple flight, hotel, and car rental APIs to provide a one-stop shop for customers to plan their trips. By integrating these different APIs, the application can offer a wider range of options and provide a more personalized experience for the user.

Cost BenefitsAnchor

It can also help save enormous costs, integrating multiple REST APIs can save a significant amount of money for businesses compared to building the functionality in-house. By using pre-existing APIs, businesses can take advantage of the development and maintenance that has already been done, rather than having to invest in building and maintaining their own systems. Additionally, the costs associated with integration, such as testing and development, are typically lower than those associated with building from scratch.

Furthermore, building an API in-house can be a time-consuming and complex process, especially for businesses that lack the necessary technical expertise. By using pre-existing APIs, businesses can get up and running quickly, without having to invest the time and resources required to build an API from scratch.

In addition to cost and time savings, integrating REST APIs also allows businesses to leverage the expertise of the API provider. For example, an API provider may have more experience in a specific area or have more resources to devote to security and compliance. This can help to ensure that the integrated API is of high quality and meets the necessary standards.

We shall understand how to integrate multiple external APIs with the help the of two examples

Example 1Anchor

We can have scenarios where we need to consume GraphQL APIs and Rest APIs to build a particular functionality. If you are unaware of GraphQL, please check GraphQL vs REST APIs.

The use case is that we want to show weather details on the user dashboard. Our user details reside in Hygraph and the weather API is supported by OpenWeatherMap. We will write code for a Next.js API that will fetch user details by making an API call to Hygraph and then we will use the location details of the user to get the weather details from OpenWeatherMap.

First, we will write a function to get user details from Hygraph.

import { GraphQLClient, gql } from 'graphql-request';
const { HYGRAPH_URL, HYGRAPH_PERMANENTAUTH_TOKEN } = process.env;
const client = new GraphQLClient(HYGRAPH_URL, {
headers: {
Authorization: `Bearer ${HYGRAPH_PERMANENTAUTH_TOKEN }`,
},
});
export async function getUserLocation(userEmail) {
const defaultReturnObject = { user: null };
try {
const getUserLocationQuery = gql`query getUserLocation($email: String!) {
nextUser(where: { email: $email }, stage: DRAFT) {
email
firstname
lastname
location
}
}`;
const getUserResponse = await client.request(getUserLocationQuery, { email: userEmail });
const { nextUser } = getUserResponse;
if (!nextUser) {
res.status(400).json(defaultReturnObject);
return;
}
res.status(200).json({ user: nextUser });
}
catch (err) {
console.log('getUserLocation, Something Went Wrong', err);
res.status(400).json(defaultReturnObject);
}
}

The function getUserLocation makes a GraphQL API request with a query to Hygraph requesting user details for a user and returns it. Any runtime errors that might occur have been handled.

export default async function getUserWeatherDetails(req, res) {
const { email } = req.query;
if (!email) {
res.status(400).json({ message: 'email not provided' });
return;
}
try {
const userData = await getUserLocation(email);
const { user } = userData;
if (!user) {
res.status(400).json({ message: 'user not found' });
return;
}
const weatherResponse = await axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${user.location}&appid=API_KEY`);
const weatherData = weatherResponse.data;
res.status(200).json({ weather: weatherData });
} catch (err) {
console.log('getUserWeatherDetails, Something Went Wrong', err);
res.status(400).json({ message: 'Failed to get weather details' });
}
}

getUserWeatherDetails is the main exported function where we are expecting email as a parameter in the query string of a request. We are using the getUserLocation function to fetch the user details by email from Hygraph. Then we use the user’s location to make a GET request to the OpenWeatherMap API and fetch the weather data. Any runtime errors are handled in the catch block and an appropriate message is returned to the client.

Note: Please replace API_KEY with your own API key, this will be provided by the external service provider (i.e OpenWeatherApp in this case)

This is how you can integrate multiple APIs into your backend application.

Example 2Anchor

Another use case is when you are using a headless CMS and you want to query some external data. In Hygraph, it is very easy to integrate external sources with the help of remote sources.

Use case: We have a user model in Hygraph that stores the basic details of the user like firstname, lastname, userId, and email. We want to query the external API of JSONPlaceHolder to get the user’s company and address details.

Steps

  • First, in your Hygraph app, go to Schema → Remote Sources → Add
  • Enter the Display name → userDetails,
  • Choose an API type in this case it will be → Rest.
  • Enter this Base URL → https://jsonplaceholder.typicode.com/users
  • The user fields that we want to pick up from the JSON placeholder API look like this
{
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
}

Copy this JSON object above and convert it to SDL using something like JSON2SDL, copy the output SDL. Inside your Remote source configuration in Hygraph click Add Custom Type Definition and paste the generated SDL over there. This will help Hygraph to map the fields from the REST API so that it can be seamlessly queried from the GraphQL playground.

  • Hit Save

Playground.png

Now that we have our remote source and its mapping configured, we can use it in our user model.

  • Go to your Hygraph user model, and from the right-hand side, select REST field.
  • Select the Remote Source that we configured in the previous steps, add **/{{doc.userId}} in the path field and click submit. This is because we want to query an endpoint like https://jsonplaceholder.typicode.com/users/:id

RemoteSourceConfiguration.png

  • Now you can go to your API playground and seamlessly query your remote field from there.

RemoteField.png

Our documentation on Remote sources explains in great depth all possible configurations for remote sources with your Hygraph schema.

Conclusion

In summary, this article discussed the importance of integrating multiple REST APIs in today's technology landscape. It highlighted the benefits of integrating APIs such as access to a wider range of data and functionality, improved efficiency, enhanced user experience, and cost savings compared to building the functionality in-house. The provided examples demonstrate how to integrate external APIs to your backend server, integrating multiple APIs and using remote sources in Hygraph.