पाठ 16 / 25
Calling GraphQL With 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.
A minimal client
JavaScript with fetch.
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.
त्वरित जाँच: What must a client check even when the HTTP status is 200?
- The cookie expiry
- The Content-Length only
- The errors array in the response body
- Nothing else
Answer
The errors array in the response body — Partial errors are common.