JAVASCRIPT

Executing GraphQL Queries and Mutations with Fetch API

Master making GraphQL requests for queries and mutations directly using JavaScript's native Fetch API, without relying on heavy external client libraries.

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

    if (!response.ok) {
      throw new Error(`GraphQL request failed with status: ${response.status}`);
    }

    const result = await response.json();

    if (result.errors) {
      console.error("GraphQL errors:", result.errors);
      throw new Error("GraphQL errors encountered.");
    }

    return result.data;
  } catch (error) {
    console.error("Error executing GraphQL operation:", error);
    throw error;
  }
}

// Example Query:
// const GET_PRODUCTS = `
//   query GetProducts($limit: Int) {
//     products(limit: $limit) {
//       id
//       name
//       price
//     }
//   }
// `;
// executeGraphQL("/graphql", GET_PRODUCTS, { limit: 5 })
//   .then(data => console.log("Query result:", data.products))
//   .catch(err => console.error("Query error:", err));

// Example Mutation:
// const ADD_PRODUCT = `
//   mutation AddProduct($name: String!, $price: Float!) {
//     createProduct(name: $name, price: $price) {
//       id
//       name
//     }
//   }
// `;
// executeGraphQL("/graphql", ADD_PRODUCT, { name: "New Gadget", price: 29.99 })
//   .then(data => console.log("Mutation result:", data.createProduct))
//   .catch(err => console.error("Mutation error:", err));
How it works: This snippet demonstrates how to interact with a GraphQL API using the native `fetch` API. It provides a generic function `executeGraphQL` that sends a POST request with the GraphQL query or mutation string and any associated variables. It correctly sets the `Content-Type` header and handles both successful data responses and GraphQL-specific errors, offering a lightweight alternative to full-fledged GraphQL 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