JAVASCRIPT

Execute a GraphQL Query Using JavaScript Fetch API

Send GraphQL queries to an API endpoint with Fetch. Structure POST requests using a `query` string and optional `variables` for data retrieval or mutations.

    const GRAPHQL_ENDPOINT = 'https://api.example.com/graphql';

    async function fetchGraphQLData(query, variables = {}) {
        try {
            const response = await fetch(GRAPHQL_ENDPOINT, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    // Add authorization headers if needed
                    // 'Authorization': `Bearer ${YOUR_ACCESS_TOKEN}`,
                },
                body: JSON.stringify({
                    query,
                    variables,
                }),
            });

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

            const { data, errors } = await response.json();

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

            return data;
        } catch (error) {
            console.error('Failed to fetch GraphQL data:', error);
            throw error; // Re-throw to allow caller to handle
        }
    }

    // Example GraphQL Query (fetch a list of users)
    const GET_USERS_QUERY = `
        query GetUsers($limit: Int) {
            users(limit: $limit) {
                id
                name
                email
                posts {
                    id
                    title
                }
            }
        }
    `;

    // Example usage:
    /*
    (async () => {
        try {
            const usersData = await fetchGraphQLData(GET_USERS_QUERY, { limit: 5 });
            console.log('Fetched Users:', usersData.users);

            // Example GraphQL Mutation
            const CREATE_USER_MUTATION = `
                mutation CreateUser($name: String!, $email: String!) {
                    createUser(input: { name: $name, email: $email }) {
                        id
                        name
                        email
                    }
                }
            `;
            const newUser = await fetchGraphQLData(CREATE_USER_MUTATION, {
                name: 'Jane Doe',
                email: '[email protected]'
            });
            console.log('Created User:', newUser.createUser);

        } catch (error) {
            console.error('Operation failed:', error);
        }
    })();
    */
How it works: This snippet provides a reusable function `fetchGraphQLData` for interacting with a GraphQL API. It constructs a `POST` request, sending the GraphQL `query` string and any associated `variables` in the request body as JSON. The function handles network errors and parses the GraphQL response, returning the `data` payload or throwing an error if GraphQL query errors are present. This pattern allows for executing both queries and mutations against a GraphQL endpoint.

Need help integrating this into your project?

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

Hire DigitalCodeLabs