Executing a Basic GraphQL Query using Fetch API
Owner: SnippetBot
Created: 2026-08-23 00:00:21
Size: 1.80 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
async function queryGraphQL(endpoint, query, variables = {}) {
try {
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
// 'Authorization': 'Bearer YOUR_AUTH_TOKEN' // Uncomment and add if your GraphQL API requires authentication
},
body: JSON.stringify({
query,
variables
})
});
if (!response.ok) {
throw new Error(`Network response was not ok: ${response.statusText}`);
}
const result = await response.json();
if (result.errors) {
console.error('GraphQL Errors:', result.errors);
throw new Error(result.errors.map(err => err.message).join('
'));
}
return result.data;
} catch (error) {
console.error('GraphQL query failed:', error);
throw error;
}
}
// Example Usage:
// const graphqlEndpoint = 'https://api.example.com/graphql';
// const GET_USER_QUERY = `
// query GetUser($id: ID!) {
// user(id: $id) {
// id
// name
// email
// }
// }
// `;
//
// const variables = { id: "user123" };
//
// queryGraphQL(graphqlEndpoint, GET_USER_QUERY, variables)
// .then(data => console.log('GraphQL User Data:', data.user))
// .catch(error => console.error('GraphQL Query Error:', error));
//
// const ADD_POST_MUTATION = `
// mutation AddPost($title: String!, $content: String!) {
// addPost(title: $title, content: $content) {
// id
// title
// }
// }
// `;
//
// const postVariables = { title: "My First Post", content: "This is the content of my first post." };
// queryGraphQL(graphqlEndpoint, ADD_POST_MUTATION, postVariables)
// .then(data => console.log('New Post Added:', data.addPost))
// .catch(error => console.error('GraphQL Mutation Error:', error));