JAVASCRIPT

Query GraphQL API with JavaScript Fetch

Learn to perform basic queries against a GraphQL API endpoint directly using the native JavaScript `fetch` API without relying on additional client libraries.

async function queryGraphQL(graphqlEndpoint, query, variables = {}) {
  try {
    const response = await fetch(graphqlEndpoint, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
        // 'Authorization': 'Bearer YOUR_AUTH_TOKEN' // Uncomment for authenticated requests
      },
      body: JSON.stringify({
        query: query,
        variables: variables
      })
    });

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

    const result = await response.json();

    if (result.errors) {
      console.error('GraphQL errors:', result.errors);
      throw new Error('GraphQL operation completed with errors.');
    }

    return result.data;
  } catch (error) {
    console.error('Error querying GraphQL API:', error);
    throw error;
  }
}

// Example Usage:
// const GQL_ENDPOINT = 'https://countries.trevorblades.com/'; // Public GraphQL API example
// const GQL_QUERY = `
//   query GetContinentCountries($code: ID!) {
//     continent(code: $code) {
//       name
//       countries {
//         code
//         name
//       }
//     }
//   }
// `;
//
// (async () => {
//   try {
//     const data = await queryGraphQL(GQL_ENDPOINT, GQL_QUERY, { code: 'EU' });
//     console.log('European Countries:', data.continent.countries.map(c => c.name));
//   } catch (error) {
//     console.error('Failed to fetch data from GraphQL:', error);
//   }
// })();
How it works: This snippet demonstrates how to interact with a GraphQL API using the native `fetch` API. Unlike REST, GraphQL typically uses a single endpoint where all queries and mutations are sent via a POST request. The `Content-Type` header is set to `application/json`, and the request body contains a JSON object with at least a `query` string and optionally `variables` for dynamic input. The function also includes basic error handling for both HTTP errors and GraphQL-specific errors returned in the `errors` field of the JSON response.

Need help integrating this into your project?

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

Hire DigitalCodeLabs