Easily restore your project to a previous version with our new Instant One-click Backup Recovery

How to run multiple GraphQL queries and combine multiple sources

Let's take a look into how to combine multiple GraphQL queries and also multiple GraphQL sources.
Joel Olawanle

Joel Olawanle

Dec 08, 2022
how to combine graphql queries

GraphQL is a query language for APIs and a runtime for fulfilling those queries. Queries are one of the various available operations in GraphQL, and are used whenever we need to fetch some data from a GraphQL API, similar to a GET request in a REST API you use. Unlike REST APIs, in GraphQL client side queries define that extract data structures and fields that we want to retrieve, and the server provides the data as per the request.

For example, we can retrieve a list of authors from a GraphQL API using the following query to get their first and last names only:

{
authors {
first_name
last_name
}
}

When we execute the above query, it will get our data in our expected format as shown below:

{
"data": {
"authors": [
{
"first_name": "John",
"last_name": "Doe"
},
{
"first_name": "Jane",
"last_name": "Dan"
}
]
}
}

If you are coming from REST API background, you might be used to make multiple API calls to get different data. For instance, a complex dashboard UI might be gathering data from 10 different rest API endpoints, but with GraphQL we can just use one round trip to the server and get all required the data at once.

In this article, we will learn how to combine multiple GraphQL queries into a single query and also how to combine data from multiple GraphQL sources into a Hygraph project.

#Why combine GraphQL queries?

There are several beneficial reasons you'll want to combine multiple GraphQL queries into one:

  • It optimizes the number of network requests, instead of 5 API calls to the server we need to make only one.
  • It helps to minimize effort required in writing the client side code and also keeps the codebase more organized.
  • It is easier to build complex UI components that need data from different data points.

Editor's Note

It is best to combine the queries if you need to pull data from more than one data point in the same component or page.

#How to combine multiple queries

A GraphQL request can contain more than one query. For example, if you want to fetch all posts from an API and also all authors, you'll find yourself using two separate GraphQL queries:

*// Query to get all authors*
query getAuthors {
authors {
firstName
lastName
}
}
*// Query to get all posts*
query getPosts {
posts {
id
title
exert
}
}

While we can execute these two queries separately it will result in two network requests, whereas we can reduce this to one by combining these queries. We can combine multiple queries by defining a new query and placing all our existing queries inside it, as you can see below:

query getAllPostsAndAuthors {
posts {
id
title
exert
}
authors {
firstName
lastName
}
}

This single query will make one API call to the GraphQL server, fetch both posts and authors and will return two arrays with the key posts and authors as shown below

{
"data": {
"posts": [
{
"id": "clbaq61t504u00b11za7oo84d",
"title": "Vue.js vs React - How to Choose the Right Framework",
"exert": "In this article, we will compare two excellent JavaScript frameworks, their pros, and cons, as well as some use cases built with each of..."
}
],
"authors": [
{
"firstName": "Daniel",
"lastName": "John"
}
]
}
}

You can also pass arguments into any subquery as per your wish. For example, let's say we want to get posts that contains the term “graphql” somewhere in the title. We can change our query as shown below.

query getAllPostsAndAuthors {
posts(where: {
title_contains:"graphql"
}){
id
title
exert
}
authors {
firstName
lastName
}
}

This is possible out of the box with the GraphQL API Hygraph provides, otherwise how you can filter the data will depend on the server implementation.

#How to combine multiple sources (multiple GraphQL APIs)

Today, there are lots of public APIs that we can leverage to get specific data, but this means making an extra request from our application. Interestingly, we at Hygraph support Remote Sources, using which we can integrate external APIs right into our Hygraph schema and query the external data seamlessly as if it is a part of our existing data. Content Federation involves merging/combining multiple data sources into our API. It allows us to combine data from various sources into our project so we can query them at once through our GraphQL API. We can integrate both REST and GraphQL APIs with Hygraph.

undefined

To properly understand how this works, let us suppose that we have a model in our Hygraph project with the name Author, and this model has fields like First Name, Last Name, Bio, Display Picture, and a reference field that links with posts published by the author from the Posts schema.

undefined

Let us further suppose that we need more information about the author, details based on the existing information. For example, we should be able to access country related information for the author (like the flag, country languages, currency, capital) and we do not want to manage the country related data in our database but instead use an existing external API for it. We can do it out of the box in Hygraph using remote sources.

We will learn how to combine two external GraphQL APIs (Countries API and Cocktail API) into our Hygraph project and query all the data with a single GraphQL query from client side. Basically, the client would not even know that the data is coming from different places.

Let's add a new field to the Author schema. This field will be the Country code; we will use this code to query for data related to that country from the Countries API that we'll be adding as a remote source.

undefined

Let's now proceed to add a remote source to the Hygraph project. This can be done by navigating to the schema tab and clicking on Remote sources. A form will appear in which we can fill in the required information, such as the name and external API ( REST or GraphQL API). For this article, both remote sources would be GraphQL APIs.

1.gif

After adding a remote source, it's time to add a remote field to a model. This will help us to set arguments that can be used to query the external API and show the data that we need. For example, we would want to send the country code to the external API to fetch country information.

Editor's Note

We can only add a remote field after at least one remote source of the corresponding type has been configured. If it is a GraphQL API, you can only create a GraphQL remote field; the same applies to REST.

2.gif

In the above demo, a GraphQL remote field is added for the remote country API. We will receive a list of entry points in the query field. We can select the entry point from which we want to get data and pass arguments. In the above example, we are getting a particular country from the list of countries whose country code matches the author's country code.

We can now test if it works by adding content to the author schema, so it fetches the author's country info based on the county code.

3.gif

In Hygraph, we are not just limited to one remote source. Depending on our account plan, we can add as many remote sources as required. Let's add a second remote source to this project to illustrate that we can add multiple sources and also query all the sources with one GraphQL query.

This second remote source would be a Cocktail API. The authors can provide the name of their favorite cocktail, and we can use the data supplied to get more information about the cocktail, such as the ingredient, instructions on how to make it, and lots more. This is done using the same process.

Step 1: Add a remote source

Like we added the remote source country API, we can also add the Cocktail API by following the same steps.

4.gif

Step 2: Create a GraphQL remote field

Before creating the remote field, we can create a field for the data we will use to query for a particular cocktail. For this, we will create two fields, the "Best cocktail" field for the author to submit the best cocktail of his/her choice, then a slug field (Cocktail Slug) that will automatically convert the "Best cocktail" data to slug.

We can now create the GraphQL remote field to query for a particular cocktail with the slug value.

5.gif

Step 3: Test the remote source

We have created a GraphQL remote field for the cocktail Info. Let's now test it by adding the author's best cocktail, which would generate a slug value, and then we can use it to get the particular cocktail information.

6.gif

At this point, we have successfully added and combined multiple remote sources into our Hygraph project. Let's now create a GraphQL query to fetch the author's data, including the name, country name, and flag alongside the author's best cocktail, its ingredients, and the instructions for making it.

query AuthorsInfo {
authors {
firstName
lastName
bio
bestCocktail
cocktailInfo {
info
ingredients
instructions
}
countryInfo {
name
emoji
capital
code
currency
}
}
}

This will return all the various values, including the ones from the remote sources in a single place

{
"data": {
"authors": [
{
"firstName": "John ",
"lastName": "Doe",
"bio": null,
"bestCocktail": "paloma",
"cocktailInfo": {
"info": "Alcoholic",
"ingredients": "Grape Soda Tequila",
"instructions": "Stir Together And Serve Over Ice."
},
"countryInfo": {
"name": "Brazil",
"emoji": "🇧🇷",
"capital": "Brasília",
"code": "BR",
"currency": "BRL"
}
}
]
}
}

This is one of the superpowers that Hygraph possesses, and GraphQL provides. You can explore more by reading the remote sources documentation and this guide and talk on content federation.

#Conclusion

In this article, we have learned the advantages of running multiple GraphQL queries at once. Also, we went through how to add multiple sources to our Hygraph project and fetch data from external APIs alongside our original data using a single GraphQL query.

Thanks for reading, and have fun coding!

Blog Author

Joel Olawanle

Joel Olawanle

Joel Olawanle is a Frontend Engineer and Technical writer based in Nigeria who is interested in making the web accessible to everyone by always looking for ways to give back to the tech community. He has a love for community building and open source.

Share with others

Sign up for our newsletter!

Be the first to know about releases and industry news and insights.