# Calling GraphQL With fetch — GraphQL

Source: https://www.skillbyai.com/en/graphql/k-fetch

> No library required.

## A POST with JSON

Any HTTP client can call GraphQL: POST JSON with `query` and `variables` and read `data` and `errors` from the response. This is enough for scripts, server-to-server calls and small apps. Remember to check the `errors` array even when the HTTP status is 200, send authentication headers, and keep queries as constants rather than building them from user input.

## Fetch, cache, type

Clients range from a plain fetch call to libraries with normalised caches and generated types.

![Three ideas: plain HTTP clients, caching clients, code generation.](assets/figures/graphql/section-6-map.svg) — Figure 6.1 — Plain fetch, caches and codegen.

## A minimal client

JavaScript with fetch.

```javascript
const QUERY = `query Product($id: ID!) { product(id: $id) { id name price } }`;

async function getProduct(id) {
  const res = await fetch("https://api.example.com/graphql", {
    method: "POST",
    headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
    body: JSON.stringify({ query: QUERY, variables: { id } }),
  });
  const { data, errors } = await res.json();
  if (errors?.length) throw new Error(errors.map((e) => e.message).join("; "));
  return data.product;
}
```

## Use operation names

Named operations appear in server logs and traces, which makes debugging much easier.

**Quiz:** What must a client check even when the HTTP status is 200?

- [ ] The cookie expiry
- [ ] The Content-Length only
- [x] The errors array in the response body
- [ ] Nothing else

*Answer:* The errors array in the response body. Partial errors are common.
