ARTICLE - Dev Stack & Tools

GraphQL Backend API Development

A GraphQL schema defines the field contract and resolvers fetch data; combining client requests does not automatically solve backend N+1 queries or authorization.

2026-08-06 GraphQL Official Documentation 37 views
Advertisement

When clients need different fields, a typed GraphQL schema lets them declare the data they need, but one client request can still trigger many backend queries. Run a local query and mutation first, then examine field authorization, batching, and resource limits before considering production use.

Schema and request execution

The schema defines fields, arguments, and return types; resolvers obtain values from memory, a database, or another service. String! means an output field cannot be null. [Article!]! means neither the list nor its elements can be null; it does not require a nonempty list. The request path below also shows where N+1 can arise.

GraphQL query request path Client query Parse and validate Resolve fields Return response Per-item related lookups can produce N+1 Basis: conceptual path of one query
Figure 1: GraphQL query request path (Source: conceptual path of one query)

GraphQL does not require a particular transport; HTTP is a common choice. REST can also offer aggregation endpoints, field selection, and typed contracts, so compare actual requirements rather than counting endpoints. A GraphQL response can contain partial data alongside errors; request errors during parsing or validation do not execute resolvers. See the GraphQL response documentation, checked on 2026-11-28.

Run a local query and mutation

You need Node.js, npm, curl, and an available local port 4000. Run this example only in an isolated directory; it does not connect to a database. Following the GraphQL.js Express guide, install express, graphql-http, and graphql; this example uses CommonJS. In a new temporary directory run:

npm init -y
npm install express graphql-http graphql

Successful installation creates package.json and node_modules in the current directory. If it fails, check whether Node.js meets the packages' requirements and whether npm can reach the registry. Save the following as server.js in the same directory:

const express = require('express');
const { buildSchema } = require('graphql');
const { createHandler } = require('graphql-http/lib/use/express');

const schema = buildSchema(`
  type Article { id: ID!, title: String! }
  type Query { article(id: ID!): Article }
  type Mutation { setTitle(id: ID!, title: String!): Article }
`);
const articles = { '1': { id: '1', title: 'First article' } };
const root = {
  article: ({ id }) => articles[id] || null,
  setTitle: ({ id, title }) => {
    if (!articles[id]) return null;
    articles[id].title = title;
    return articles[id];
  },
};
const app = express();
app.all('/graphql', createHandler({ schema, rootValue: root }));
app.listen(4000, '127.0.0.1', () => console.log('Listening on 127.0.0.1:4000'));

This stateful in-memory demonstration has no authentication, persistence, or input length limit. It binds only to the loopback address and must not be deployed publicly as-is. Run node server.js; the listening message means the process started. If the port is occupied, stop the conflicting process or change the port and update the addresses below.

In another terminal, send a query with variables separate from the query text:

curl -sS http://127.0.0.1:4000/graphql \
  -H 'Content-Type: application/json' \
  --data '{"query":"query GetArticle($id: ID!) { article(id: $id) { id title } }","variables":{"id":"1"}}'

The JSON response should contain ID 1 and title First article in data.article. If the connection fails, check the process and port; if it contains errors, check the queried fields and variable types.

Then send a mutation:

curl -sS http://127.0.0.1:4000/graphql \
  -H 'Content-Type: application/json' \
  --data '{"query":"mutation Rename($id: ID!, $title: String!) { setTitle(id: $id, title: $title) { id title } }","variables":{"id":"1","title":"Updated article"}}'

data.setTitle.title should be Updated article; repeating the query should return that title too. An unknown ID returns null. Stop the service with Ctrl-C; restarting resets the in-memory data, which is also the rollback for this example.

Control N+1, pagination, and errors

If each Article in a list loads its author separately, one list query can lead to many author lookups. Create a DataLoader per request to batch keys in the same execution frame. Its batch function must return an equally sized array in key order; a missing item can be null or an Error. Different execution frames, database limits, or downstream services can still require multiple queries, so a single lookup per request is not guaranteed. Compare database query logs before and after the change and isolate caches by user and tenant.

Limit page size and use stable ordering and cursors. Concurrent insertions, deletions, or changes to sort keys still require explicit consistency semantics; cursors do not automatically eliminate duplicates or omissions. Cross-request caches must account for identity, tenant, and invalidation; DataLoader's request-local cache is not a substitute.

According to the GraphQL response documentation, execution errors can return both data and errors; a non-null field failure propagates to the nearest nullable parent. A request validation error may have no data, while expected business failures can be represented as typed schema results. Clients should handle the HTTP layer, errors, and partial data rather than relying on status alone.

Security and evolution before launch

After authentication, authorize each object and sensitive field. An object may be reached through multiple paths, so protecting only the root field is insufficient. Bound page sizes, query depth, aliases, and batched requests, and use complexity or rate budgets based on field cost. Depth limits alone do not control wide queries. Set actual thresholds using your data and load tests; see the GraphQL security guide, checked on 2026-11-28.

Adding an optional field is generally easier to accommodate than removing or changing a field's type, but check client usage. Deprecate the old field, observe usage and notify consumers before scheduling removal. Automated schema-diff checks help but do not replace client compatibility tests. HTTPS, timeouts, error redaction, and parameterized database queries also apply.

Limitations

  • The sample demonstrates local HTTP and in-memory reads and writes only. It has no authentication, authorization, persistence, pagination, rate limits, or DataLoader and is not production-ready.
  • subscription execution and transport require additional implementation, commonly WebSocket or SSE; the sample does not support subscriptions.
  • GraphQL and REST can coexist. HTTP caching depends on request method, cache configuration, and data permissions, not the interface name alone.

FAQ

What should I check when a query returns null?

Inspect both data and errors. A missing object can legitimately yield null for a nullable field; an execution failure may include an error path, while a non-null constraint can propagate null to a parent. If syntax or type validation fails, resolvers do not run and the response may omit data.

Why create DataLoader per request?

Each instance maintains a cache. Sharing one between users or tenants can expose another user's result or leave stale values across requests. Create loaders per request and enforce permissions in the batch function. This still does not ensure every load is grouped into one batch; verify using backend query logs.

Can a GraphQL API omit mutations?

Yes. A read-only service can expose only Query. Add Mutation only when writes are needed, and enforce authorization, input validation, and persistence in the relevant resolver. Passing GraphQL type validation does not establish that business input is safe or that the caller may modify a resource.

Related Providers

  • Node.js: run the JavaScript local example and server applications.
  • PostgreSQL: use as a data source when an application needs relational persistence and batch queries.

Community & Resources

Original source: GraphQL Official Documentation ↗