JAVASCRIPT

Execute a Simple GraphQL Query using `fetch` in JavaScript

Learn to perform basic GraphQL queries and mutations from a client-side JavaScript application using the native `fetch` API, without external libraries.

async function executeGraphQLQuery(endpoint, query, variables = {}, headers = {}) {
    try {
        const response = await fetch(endpoint, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                ...headers // Allow custom headers like Authorization
            },
            body: JSON.stringify({
                query: query,
                variables: variables
            })
        });

        if (!response.ok) {
            const errorBody = await response.text();
            throw new Error(`GraphQL network error: ${response.status} ${response.statusText}. Response: ${errorBody}`);
        }

        const data = await response.json();

        if (data.errors) {
            console.error('GraphQL errors:', data.errors);
            throw new Error('GraphQL query failed with errors.');
        }

        return data.data; // Return the actual data payload
    } catch (error) {
        console.error('Error executing GraphQL query:', error);
        throw error;
    }
}

// Example usage:
// (async () => {
//     const graphqlEndpoint = 'https://countries.trevorblades.com/'; // Public GraphQL API example
//     const countryQuery = `
//         query GetCountry($code: ID!) {
//             country(code: $code) {
//                 name
//                 capital
//                 currency
//                 languages {
//                     name
//                 }
//             }
//         }
//     `;
//     const countryVariables = { code: 'BR' }; // Example: Brazil

//     try {
//         const result = await executeGraphQLQuery(graphqlEndpoint, countryQuery, countryVariables);
//         console.log('GraphQL Query Result:', JSON.stringify(result, null, 2));
//         if (result && result.country) {
//             console.log(`Country: ${result.country.name}, Capital: ${result.country.capital}`);
//         }
//     } catch (error) {
//         console.error('Failed to fetch country data:', error.message);
//     }

//     // Example for a mutation (structure would be similar, just different query string)
//     // const createItemMutation = `
//     //     mutation CreateItem($name: String!) {
//     //         createItem(name: $name) {
//     //             id
//     //             name
//     //         }
//     //     }
//     // `;
//     // const mutationVariables = { name: 'New Widget' };
//     // try {
//     //     const mutationResult = await executeGraphQLQuery('YOUR_GRAPHQL_API_ENDPOINT', createItemMutation, mutationVariables);
//     //     console.log('Mutation Result:', mutationResult);
//     // } catch (error) {
//     //     console.error('Failed to execute mutation:', error.message);
//     // }
// })();
How it works: This JavaScript snippet demonstrates how to interact with a GraphQL API using the native `fetch` API without relying on dedicated client libraries. The `executeGraphQLQuery` function sends a POST request with the GraphQL query string and any variables in the JSON request body. It handles both successful responses and GraphQL-specific error reporting, making it a foundational method for integrating GraphQL into web applications.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs