How to Fetch Data Using GraphQL API with Vanilla JavaScript

GraphQL is a query language for your API and a server-side runtime for executing queries using a type system you define for your data. It allows developers to access specific data from APIs. GraphQL is a flexible alternative to REST as the server knows exactly what the client is asking for.

In this article, we are going to learn how to fetch data from GraphQL in Vanilla JavaScript using the fetch method.

What is a GraphQL query

Queries are what developers use to fetch data from the API. A GraphQL query returns the specific data from the API just as requested. The below query returns the name and code of continents from the countries API.

How it Works

GraphQL Query:

query {
        continents {
            name 
            code
        }
    }

GraphQL Output:

{
  "data": {
    "continents": [
      {
        "name": "Africa",
        "code": "AF"
      },
      {
        "name": "Antarctica",
        "code": "AN"
      },
      {
        "name": "Asia",
        "code": "AS"
      },
      {
        "name": "Europe",
        "code": "EU"
      },
      {
        "name": "North America",
        "code": "NA"
      },
      {
        "name": "Oceania",
        "code": "OC"
      },
      {
        "name": "South America",
        "code": "SA"
      }
    ]
  }
}

You can learn more about GraphQL queries and mutations here.

How to Fetch the Data Using Vanilla JavaScript

The fetch() method allows you to send requests to the GraphQL API. You will also need. To specify the metadata inline with the API call, use the headers interface with the content-type indicated as you are sending JSON. You will then include the request body which will have the query arguments being sent to the API. Now that the request has been sent, you can view the response in your console.

fetch('https://countries.trevorblades.com', {
method: 'POST',
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
    query: ` {
        continents {
            name 
            code
        }
    }
    `
})
})
.then(res => res.json())
.then(data => {
    console.log(data.data.continents)
})

Code Output in the Console:

Image description

As you can see, the API call returns the name and code of each continent in our console. You can check the GraphQL API playground here for further documentation on more data you could fetch.

Conclusion

In this article, you were able to learn how GraphQL queries simplify fetching data from the GraphQL API and how to fetch data in JavaScript. GraphQL is an interactive query language for APIs that is a great alternative to REST and is complex to allow implementation with many languages as well.