Here's a quick summary of everything we released in Q1 2024.

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 used to interact with an API. As a query language, whenever you need to fetch data from a GraphQL API, you use GraphQL queries. These queries define the data you want to retrieve, so the server provides the data in the "exact" same structure as your query.

For example, you 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 you execute the above query, it will get your data in the exact format as seen below:

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

You are often only used to making one query at a time, and if you need to make multiple related queries on a single page, you decide to separate them because you have yet to learn that multiple queries exist.

In this article, you'll learn how to combine multiple GraphQL queries into a single query and combine data from multiple GraphQL sources into your Hygraph project.

#Why combine GraphQL queries?

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

  • It allows for retrieving multiple data points in a single request, reducing the number of requests to the server and increasing the application's speed.
  • It allows for better organization of data and more efficient interactions with the server.

There are many more reasons, but in general, you make only one request to your server, which improves performance, rather than having to make several requests, which can be costly.

#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
}
}

But having two queries run differently on one component can be more expensive because you are making two calls to your API, whereas you can reduce this to one by combining these queries. You can combine multiple queries by defining a query and placing all your queries within, as you can see below:

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

This will return two arrays with the key posts and authors, meaning if you are calling this into a JavaScript project, you can destructure and have access to both arrays without using the dot operator.

{
"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 query and manipulate your query as you wish.

#How to combine multiple sources (multiple GraphQL APIs)

Previously, when you develop API, you'll have to create all your fields and supply the appropriate content into your API. These days, there are lots of public APIs you can leverage to get specific data, but this means making an extra request within your application. How about integrating your preferred external API into your database and getting the data you want alongside other data from your database?

In Headless CMS, this is why you have Content Federation. Content federation involves merging/combining multiple data sources into your API. This means you can combine data from various sources into your project so you can query them at once through your GraphQL API.

What is Content Federation and how does it unify your stack? | Hygraph

To properly understand how this works, suppose you have a model in your Hygraph project with the name Author, which 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.

Hygraph dashboard

If, in your application or for company data, you need more information about the author, like details based on the supplied information. For example, you should be able to access more information (flag emoji, country languages, currency, capital, and lots more) about the author's country if the country name or code is supplied instead of entering this data manually for each author, which can be time-consuming.

For this article, you will learn how to combine two external GraphQL APIs (Countries API and Cocktail API) into your Hygraph project and query for data with a single GraphQL query.

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

adding a country code field

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

adding a remote source to hygraph

After adding a remote source, it's time to add a remote field to a model. This will help you set arguments that will be used to query the external API and show your needed data. For example, you want to use the country code provided by the user to fetch country information.

adding a remote source to the schema

In the above GIF, a GraphQL remote field is added for the remote country API that was added. You will receive a list of entry points in the query field. You will select the entry point from which you want to get data and pass an argument. In the above example, you are getting a particular country from the list of countries whose country code matches the author's country code.

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

testing the remote source data for an existing content entry

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

This second remote source would be a Cocktail API. The authors are expected to provide the name of their favorite cocktail, so you will 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 you added the remote source country API, you can also add the Cocktail API by following the same steps.

adding another remote source to hygraph

Step 2: Create a GraphQL remote field

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

adding the field to the schema

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

adding a remote field

Step 3: Test the remote source

You 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 you can use it to get the particular cocktail information.

testing the remote field in the graphql playground

At this point, you have successfully added and combined multiple remote sources into your 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, directly into this GraphQL query:

{
"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, you have learned the advantages of running multiple GraphQL queries at once. Also, you have learned how to add multiple sources to your Hygraph project so you can fetch its data alongside your original data using a single GraphQL query.

Thanks for reading, and have fun coding!

The GraphQL Report 2024

Statistics and best practices from prominent GraphQL users.

Check out the report

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.