JAVASCRIPT

Client-Side Integration with a GraphQL API (Basic Query)

Discover how to send a basic GraphQL query from a web client using the standard `fetch` API, enabling seamless interaction with GraphQL endpoints.

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

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

    const result = await response.json();

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

    return result.data; // Contains the actual data returned by the query
  } catch (error) {
    console.error('Error querying GraphQL API:', error);
    throw error;
  }
}

// Example Usage:
// const MY_GRAPHQL_ENDPOINT = 'https://api.example.com/graphql';
// const GET_USER_QUERY = `
//   query GetUser($id: ID!) {
//     user(id: $id) {
//       id
//       name
//       email
//     }
//   }
// `;
//
// queryGraphQL(MY_GRAPHQL_ENDPOINT, GET_USER_QUERY, { id: "123" })
//   .then(data => console.log('GraphQL User Data:', data.user))
//   .catch(error => console.error('Failed to get user data:', error));
How it works: This snippet illustrates how to perform a basic GraphQL query from a client-side JavaScript application. It uses the standard `fetch` API to send a POST request to a GraphQL endpoint. The query and optional variables are included in the request body as a JSON object. The response is then parsed, and any GraphQL-specific errors are checked before returning the actual data. This provides a foundational approach for interacting with GraphQL APIs without relying on client libraries.

Need help integrating this into your project?

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

Hire DigitalCodeLabs