Skip to main content
CodingMarble

Web development

REST vs GraphQL: How to Choose an API Style

REST exposes many URLs that each return a fixed resource, while GraphQL exposes one endpoint where the client describes the exact shape of data it wants. For a small team with a handful of clients, REST is usually the simpler default; GraphQL pays off when many different screens or apps need different slices of the same data.

By CodingMarble · Published · 6 min read

A silver iMac on a desk in a bright room
Photo: Lee Campbell on Unsplash

How each style works

REST organises an API around resources. Each thing in your system, such as a user or an order, has a URL, and standard HTTP methods act on it: GET reads, POST creates, PUT or PATCH changes, DELETE removes. The server decides what each URL returns. Because every request is a plain HTTP request to a stable URL, the whole web toolchain (browsers, proxies, CDNs, curl) understands it without extra help.

GraphQL organises an API around a typed schema. There is normally a single endpoint, and the client sends a query that names the fields it wants, including fields on related objects. The server walks the query, calls a resolver function for each field, and returns JSON shaped exactly like the question. Nothing about GraphQL requires a special database or language; it is a contract and a query language sitting in front of whatever data sources you already have.

They move complexity to different places. REST keeps the server simple per route and pushes some work onto the client, which may need several calls. GraphQL keeps the client simple and pushes work onto the server, which must plan and protect arbitrary queries.

The same question in both styles

Suppose a profile screen needs a user's name and the titles of their three most recent posts. In REST you might make two requests, or one if the API designer added an embed option. In GraphQL it is one request, and the response contains only what was named.

Shell· REST: two calls, each returns the full resource
curl https://api.example.com/users/42
curl "https://api.example.com/users/42/posts?limit=3&sort=-created_at"
Prompt· GraphQL: one POST to /graphql with this query in the JSON body
query ProfileScreen {
  user(id: 42) {
    name
    posts(first: 3) {
      title
    }
  }
}

The REST user response probably includes an email, address, preferences and a dozen other fields the screen never shows. The GraphQL response contains name and post titles only. That difference is the heart of the debate, so it deserves a careful look rather than a slogan.

Over-fetching and under-fetching

Over-fetching means the response carries data the screen does not use. Under-fetching means one request is not enough, so the client chains calls: fetch the user, then fetch posts, then fetch each post's author. On a fast office network neither hurts much. On a mobile connection with high latency, several sequential round trips are noticeable, and large payloads cost data and battery.

GraphQL addresses both by letting the client ask for exactly one tree of data. REST has its own answers, and they are often enough: sparse field selection with a parameter such as fields=name,email, optional embedding with an include parameter, or a purpose-built endpoint for a heavy screen, sometimes called a backend-for-frontend route. Those are less flexible than GraphQL but far cheaper to build and secure.

Before choosing, measure your own situation. Open the browser network panel on your slowest screen and count the requests and the bytes. If it is two small calls, the problem GraphQL solves may not exist for you yet.

Caching: HTTP caches versus client caches

REST benefits from HTTP caching almost for free. A GET to a URL can carry Cache-Control and ETag headers, and browsers, CDNs and reverse proxies can then store or revalidate the response without knowing anything about your data. A public product list can be served from the edge without touching your server.

GraphQL usually sends queries as POST requests to one URL, and caches do not store POST responses by default. Every request looks identical at the URL level, so a CDN cannot tell them apart. Teams work around this with persisted queries, where the client sends a short query identifier over GET so the URL varies per query, but that is extra setup, not a default.

What GraphQL offers instead is a smart client cache. Libraries such as Apollo Client, urql and Relay store results by type and id, so when a mutation returns an updated user, every screen showing that user updates. This is powerful for interactive apps, but it is cache logic you now own and must debug. Neither approach is wrong; they cache at different layers.

Practical tip: whichever style you pick, decide per data type what may be cached and for how long before writing endpoints. Public, rarely changing data suits edge caching; user-specific data should send Cache-Control: private or no-store.

Versioning and evolving the API

REST APIs are commonly versioned with a path prefix such as /v2/ or a header. A breaking change means shipping a new version and keeping the old one alive while clients migrate. It is explicit and easy to reason about, but maintaining two versions has a real cost.

GraphQL's usual approach is continuous evolution. Because clients name every field they use, you can add new fields and types at any time without affecting anyone. To retire a field you mark it deprecated in the schema, watch which clients still request it, and remove it when usage stops. This works well only if you actually track field usage, which requires tooling or logging on your side.

Be honest about the failure mode in each. REST drifts into many versions that nobody dares to delete. GraphQL drifts into a schema full of deprecated fields because nobody checks who still calls them.

Tooling, typing and error handling

GraphQL's schema is its biggest practical advantage. It is machine-readable, so you can generate TypeScript types, validate queries in the editor and browse documentation interactively. REST can reach a similar place with an OpenAPI description, from which types and clients can also be generated, but that description is a separate file that must be kept in sync with the code unless your framework produces it for you.

Error handling differs in a way that surprises newcomers. REST uses HTTP status codes: 404 for missing, 401 for unauthenticated, 422 or 400 for invalid input, 500 for server faults. Monitoring tools understand these out of the box. A GraphQL server commonly answers 200 even when part of the query failed, and reports problems in an errors array next to whatever data could be resolved. That allows partial results, which is useful, but it means your uptime dashboards must look inside response bodies, not only at status codes.

JSON· A GraphQL response with partial data and an error
{
  "data": {
    "user": { "name": "Asha", "posts": null }
  },
  "errors": [
    {
      "message": "Not allowed to read posts",
      "path": ["user", "posts"]
    }
  ]
}

Security concerns specific to GraphQL

In REST you control the cost of each route because you wrote it. In GraphQL the client composes the query, and relationships can be nested without end: a user's posts, each post's comments, each comment's author, that author's posts, and so on. A hostile or careless client can ask for an expensive tree in one request.

The standard defences are to limit query depth, to assign a cost to fields and reject queries above a budget, to cap list sizes such as first: 100, to set request timeouts, and to rate limit by cost instead of by request count. Persisted queries go further by allowing only queries you have approved in advance. Authorisation also needs care: check permissions inside resolvers, not only at the endpoint, because one query can touch many types.

Another trap is the N+1 problem: a list of 50 posts triggers 50 separate author lookups because each resolver runs independently. Batching with a loader pattern fixes it. Test for it by logging database queries while running a nested query.

Which one fits a small team

Choose REST when you have one web client, perhaps one mobile app, a mostly resource-shaped domain, and a team that wants to ship quickly with ordinary tools. You get HTTP caching, simple debugging with curl, and status-code monitoring without learning a new stack.

Choose GraphQL when many screens or several client apps need different shapes of the same connected data, when frontend and backend teams iterate at different speeds, or when you aggregate several services behind one API. Accept that you are taking on schema design, query protection and client cache behaviour.

A sensible middle path is to start with REST, add field selection or one composite endpoint where a screen is slow, and revisit GraphQL only if you find yourself writing many one-off endpoints. Whichever you choose, write the contract down (OpenAPI or a schema), keep it versioned in your repository, and generate types from it so the frontend and backend cannot silently disagree.

Need this built properly for your business?

CodingMarble is a remote studio in India that builds websites, apps and games on fixed packages with the scope written down before payment. Try the free tools we run, or start a project when you are ready.