JAVASCRIPT

Consume a GraphQL API with JavaScript Fetch

Learn how to make a POST request to a GraphQL endpoint using the native Fetch API in JavaScript to query data, demonstrating basic data retrieval.

async function fetchGraphQLData(query, variables = {}) {
  const endpoint = 'https://api.graphql.guide/graphql'; // Replace with your GraphQL endpoint
  const headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    // 'Authorization': 'Bearer YOUR_API_TOKEN' // Uncomment and add if authentication is required
  };

  try {
    const response = await fetch(endpoint, {
      method: 'POST',
      headers: headers,
      body: JSON.stringify({ query, variables })
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const result = await response.json();
    // Handle GraphQL errors if present in the response
    if (result.errors) {
      console.error('GraphQL Errors:', result.errors);
      throw new Error('GraphQL error occurred.');
    }
    return result.data;

  } catch (error) {
    console.error('Error fetching GraphQL data:', error);
    throw error; // Re-throw to allow further handling
  }
}

// Example Usage:
const GET_USERS_QUERY = `
  query GetUsers {
    users {
      id
      name
      email
    }
  }
`;

fetchGraphQLData(GET_USERS_QUERY)
  .then(data => console.log('Fetched GraphQL Data:', data))
  .catch(error => console.error('Failed to fetch users:', error));

// Example with variables:
const GET_USER_BY_ID_QUERY = `
  query GetUser($id: ID!) {
    user(id: $id) {
      id
      name
      email
    }
  }
`;

fetchGraphQLData(GET_USER_BY_ID_QUERY, { id: '123' })
  .then(data => console.log('Fetched User by ID:', data))
  .catch(error => console.error('Failed to fetch user by ID:', error));
How it works: This snippet demonstrates how to interact with a GraphQL API using the standard JavaScript Fetch API. GraphQL requests are typically POST requests with a JSON body containing the `query` (and optionally `variables` and `operationName`). The function `fetchGraphQLData` constructs this request, handles HTTP errors, and then processes the JSON response, specifically checking for and logging any GraphQL-specific errors returned in the `errors` field of the response body.

Need help integrating this into your project?

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

Hire DigitalCodeLabs