[Tip] You may not need any library to query the GraphQL API
Published: Jun 10, 2021Last Updated: Aug 12, 2024
JavaScriptGraphQLProgramming Tipsvanilla-js
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 endpoint.
Anatomy of a GraphQL query
- The query itself
- 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}),
})