JAVASCRIPT
Querying a GraphQL API with Vanilla JavaScript fetch
Discover how to make GraphQL queries and mutations directly using the vanilla JavaScript `fetch` API, enabling lightweight integrations without needing heavy client libraries.
async function fetchGraphQLData(query, variables = {}) {
const API_URL = 'https://api.graphql.example.com/graphql'; // Replace with your GraphQL endpoint
const API_TOKEN = 'YOUR_AUTH_TOKEN'; // Replace with your authentication token if required
try {
const response = await fetch(API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': `Bearer ${API_TOKEN}` // Example: if authentication is needed
},
body: JSON.stringify({
query: query,
variables: variables
})
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(`GraphQL API error: ${JSON.stringify(errorData)}`);
}
const data = await response.json();
return data.data; // GraphQL responses typically nest actual data under 'data'
} catch (error) {
console.error('Error fetching GraphQL data:', error);
throw error;
}
}
// Example Usage: Fetching a list of users
const GET_USERS_QUERY = `
query GetUsers {
users {
id
name
email
}
}
`;
fetchGraphQLData(GET_USERS_QUERY)
.then(data => {
console.log('Users:', data.users);
})
.catch(error => {
console.error('Failed to get users:', error);
});
// Example Usage: Performing a mutation
const CREATE_USER_MUTATION = `
mutation CreateUser($name: String!, $email: String!) {
createUser(name: $name, email: $email) {
id
name
}
}
`;
fetchGraphQLData(CREATE_USER_MUTATION, { name: 'Jane Doe', email: '[email protected]' })
.then(data => {
console.log('New User Created:', data.createUser);
})
.catch(error => {
console.error('Failed to create user:', error);
});
How it works: This JavaScript function demonstrates how to interact with a GraphQL API using the native `fetch` API. Unlike REST, GraphQL requests are typically POST requests with a JSON body containing a `query` string and optional `variables`. This snippet shows how to construct such a request, handle authentication, and parse the response, providing a lightweight alternative to dedicated GraphQL client libraries for simpler integrations.