GraphQL only needs one route, usually /graphql
. Unlike REST where you create routes for your resources, this approach starts to break down as soon as you need relational data and you start to add gross things to your query string. GraphQL using the actual query to resolve the resources you want, not the url path.
Unlike REST, everything in GraphQL is a POST request (you can also use GET request entirely for GQL as well but not recommended). Also, GQL does not care about status codes, as everything is a 200.
To address the status code ignorance, GQL API’s can respond to queries with JSON that have custom error messages and codes in them.
The response, if executed without errors, will always have a data
field with the query results.
Because a GraphQL query is just a string, you can use fetch to make a call.
const url = "<http://your-graphql-endpoint.com/graphql>";
const query = `
{
user(id: "1") {
name
email
posts {
title
content
}
}
}
`;
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({ query })
})
.then(response => response.json())
.then(data => console.log('Data:', data.data))
.catch(error => console.error('Error:', error));