Querying GraphQL  with Fetch API

Querying GraphQL with Fetch API

What is GraphQL:

GraphQL is a popular query language that provides a flexible and efficient way to read and mutate data from APIs (Application Programming Interfaces). It allows clients to request exactly the data they need, and nothing more, by enabling them to specify the structure of the response they want in their query.

It is an alternative to the traditional REST (Representational State Transfer) API. Here are some features of GraphQL:

  1. Single Endpoint: Unlike REST APIs which often have multiple endpoints for different resources, GraphQL typically has a single endpoint for all data queries and mutations.

  2. Declarative Data Fetching: Clients can request specific fields of data within a single query, avoiding over-fetching (getting more data than needed) or under-fetching (not getting enough data) of information.

  3. Mutations: GraphQL supports data mutations, allowing clients to create, update, and delete data as needed.

Query a GraphQL API using Fetch:

Steps to make a GraphQL query using the Fetch API in JavaScript :

  • Define the GraphQL Query: The query should be a string in the GraphQL syntax, specifying the fields and parameters you need.

      const userArticle = ` {
          user(username: "username") {
          blogHandle
          publication {
            posts(page: 0) {
              slug
              title
              contentMarkdown
            }
          }
        }
      `;
    
  • Send the Fetch Request: Use the Fetch API to send a POST request to your GraphQL API endpoint. Set the method to 'POST' and provide headers, including 'Content-Type': 'application/json'.

  • Prepare the Request Body: The body of the Fetch request should be a JSON object containing the GraphQL query string wrapped in the query field:

const options = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ query: userArticle }),
};
  • Handle the Response: Once you receive the response, you can process the data or handle any errors:

      fetch("https://api.hashnode.com/", options)
        .then(response => response.json())
        .then(data => {
          console.log(data);
        })
        .catch(error => {
          console.error(error);
        });
    

# We can also structure the code using async/await syntax to achieve the same result:

async function getArticleData{
const userArticle = ` {
    user(username: "username") {
    blogHandle
    publication {
      posts(page: 0) {
        slug
        title
        contentMarkdown
      }
    }
  }
`;

  try {
    const response = await fetch("https://api.hashnode.com/", {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ query: userArticle }),
  });
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}
getArticleData();

Note: The principle for the mutation will be practically the same as for queries, i.e. passing query and variables.

Conclusion #

This is a brief introduction to fetch usage for GraphQL queries. While on complex projects you should strive to use a GraphQL client, such as Apollo, Relay, or others, fetch has an important role, when you need to keep the project size at a minimum.