[Tip] You may not need any library to query the GraphQL API

[Tip] You may not need any library to query the GraphQL API

TLDR;

  • The request needs to be sent using the POST method
  • The query and variables need to be sent as a JSON object
// sample query
const query = `
    query HeroNameAndFriends($episode: Episode) {
        hero(episode: $episode) {
            name
            friends {
                  name
            }
      }
}
`;

const variables = {
        episode: "Some Episode Title"
    }

fetch("https://someGraphQL/endpoint", {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({query, variables}),
})

Note: if there are no variables used in the query, send an empty object. Do not omit the key entirely.

GraphQL query is just an HTTP request

Underneath the hood, the GraphQL query works by sending HTTP request(s) to a certain endpoint. Unlike the REST API, GraphQL API has only one end point.

Anatomy of a GraphQL query

  1. The query itself
  2. Any query variables
 query HeroNameAndFriends($episode: Episode) {
        hero(episode: $episode) {
            name
            friends {
                  name
            }
      }
}

This query expects to get the Hero, and their friend's name from a particular episode(variable)

Let's extract these two components into separate variables

// The query itself
const query = `
    query HeroNameAndFriends($episode: Episode) {
        hero(episode: $episode) {
            name
            friends {
                  name
            }
      }
}
`;

// Necessary Variables
const variables = {
        episode: "Some Episode Title"
    }

Using the Fetch API

  • The request method must be POST
  • The query and variables must be represented as an object and should be passed into the request body as a JSON string.
  • Necessary headers must be included(content-type, authentication, etc.)

Putting it all together

// The query itself
const query = `
    query HeroNameAndFriends($episode: Episode) {
        hero(episode: $episode) {
            name
            friends {
                  name
            }
      }
}
`;

// Necessary Variables
const variables = {
        episode: "Some Episode Title"
    }

// Using Fetch
fetch("https://someGraphQL/endpoint", {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({query, variables}),
})