← Back to all snippets
JAVASCRIPT

Fetching Data from a GraphQL API

Learn how to make a basic query to a GraphQL API using JavaScript's fetch API, demonstrating how to construct and send GraphQL requests and process the structured responses efficiently.

async function queryGraphQL(url, query, variables = {}) {
  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        // Add authorization headers if needed, e.g., 'Authorization': 'Bearer YOUR_TOKEN'
      },
      body: JSON.stringify({
        query,
        variables
      }),
    });

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

    const result = await response.json();

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

    return result.data;

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

// Usage example:
// const GRAPHQL_API_URL = 'https://countries.trevorblades.com/'; // Example public GraphQL API
// const GET_COUNTRY_QUERY = `
//   query GetCountry($code: ID!) {
//     country(code: $code) {
//       name
//       capital
//       currency
//     }
//   }
// `;
//
// queryGraphQL(GRAPHQL_API_URL, GET_COUNTRY_QUERY, { code: 'BR' })
//   .then(data => console.log('Country Data:', data.country))
//   .catch(error => console.error('Failed to get country:', error));
//
// // Example for a mutation (if your API supports it):
// // const CREATE_USER_MUTATION = `
// //   mutation CreateUser($name: String!) {
// //     createUser(name: $name) {
// //       id
// //       name
// //     }
// //   }
// // `;
// // queryGraphQL(YOUR_API_URL, CREATE_USER_MUTATION, { name: 'John Doe' })
// //   .then(data => console.log('New User:', data.createUser))
// //   .catch(error => console.error('Failed to create user:', error));
How it works: This JavaScript snippet demonstrates how to interact with a GraphQL API using the standard `fetch` API. It sends a `POST` request to the GraphQL endpoint with the `query` and `variables` (if any) serialized as a JSON string in the request body. The function handles both network-level errors and GraphQL-specific errors returned in the `errors` array of the response. This pattern is fundamental for fetching data or performing mutations in applications that consume GraphQL services.

Need help integrating this into your project?

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

Hire DigitalCodeLabs