Square CloudSquare Cloud

REST vs GraphQL: which to use for your API

REST organizes an API as URLs per resource and gets HTTP caching for free. GraphQL exposes a single endpoint where the client asks for exactly the fields it needs. Neither wins every time: it depends on who consumes the API and how the data connects.

Updated 8 min read

Learning objectives

After reading this article you will be able to:

  • Understand how requests differ between REST and GraphQL
  • Compare caching, errors, versioning and the N+1 problem
  • Decide which one fits your clients and your data
On this page

Almost every new API starts with the same question: follow the REST model, with one URL per resource, or expose a GraphQL endpoint where the client writes the query? Both run over HTTP, both send JSON, and both solve the same business problems. What changes is who decides the shape of the response and where the complexity lives.

This guide compares them on what matters day to day: how many requests a screen needs, what caches can store, how errors arrive, what each query costs on the server and how the API evolves without breaking clients.

What are REST and GraphQL?#

REST is an architectural style: each resource has a URL (/users/42, /users/42/orders) and the HTTP method says what to do (GET reads, POST creates, DELETE removes). The server defines the shape of every response, and the meaning of methods, status codes and caching comes from HTTP itself, as described in RFC 9110. The basics are in what is a REST API.

GraphQL is a query language with a type system, published as an open specification. The server describes the available types and fields in a schema, and the client sends a query naming the fields it wants, almost always as a POST to a single endpoint, usually /graphql. Each field has a function on the server, the resolver, that fetches that piece of data.

The same screen in both models:

http
GET /users/42
GET /users/42/orders?limit=3
graphql
query {
  user(id: "42") {
    name
    orders(first: 3) {
      id
      total
    }
  }
}

With REST, that's two requests, and each returns the whole resource. With GraphQL, one request returns JSON shaped exactly like the query.

How do they compare side by side?#

Criterion REST GraphQL
Endpoints One per resource One, usually /graphql
Who shapes the response The server The client, within the schema
Methods GET, POST, PUT, PATCH, DELETE POST (queries also over GET)
HTTP caching (browser, CDN) Built in for GET Only over GET, ideally with persisted queries
Errors HTTP status code errors list in the body, often with a 200
Versioning Usually in the URL (/v1/) or a header Schema evolves with @deprecated
Contract and types Optional, with OpenAPI Required: the schema itself
Cost of a request Predictable per route Varies with the query
File upload and download A plain HTTP route Outside the specification

Who picks the fields?#

Over-fetching means getting more than the screen uses: GET /users/42 returns twenty fields when the app only shows the name. Under-fetching is the opposite: one route isn't enough, so the client chains calls, one for the user, another for the orders, another for each product. On a phone with a slow network, every round trip adds latency.

GraphQL was built for this case: the client lists the fields, including those of related resources, and gets everything in one response. With REST, the options are custom routes for each screen, parameters such as ?fields=name,email or ?include=orders, or living with a few extra bytes, which is often the right call when the resource is small.

If your API has one or two clients that you write yourself and the screens mostly ask for the same data, the GraphQL gain here is small. It grows when many clients (web, Android, iOS, partners) ask for different combinations of the same data.

How does caching work?#

REST inherits HTTP caching. A response to GET with Cache-Control: max-age=60 can be stored by the browser and by a CDN, and an ETag enables revalidation: the client sends If-None-Match and the server answers 304 Not Modified with no body. None of it needs client code. The header is covered in detail in Cache-Control.

http
HTTP/1.1 200 OK
Cache-Control: public, max-age=60
ETag: "orders-42-v3"

In GraphQL, queries usually go as POST to the same URL, and RFC 9110 says a POST request cannot be satisfied by a cached POST response. There are two ways around it. The first is sending queries over GET, which the GraphQL documentation allows for reads (mutations never go over GET), ideally as persisted queries: the client sends a short hash instead of the query text, which fits within URL length limits. The second is caching in the client itself: Apollo Client, for example, keeps results in a normalized in-memory cache and reuses an object it already fetched on another screen.

What is the N+1 problem and what does a query cost?#

The N+1 problem is when fetching a list of N items costs 1 query for the list plus N more, one per item. In GraphQL, it comes from resolvers: each field is resolved by its own function, so 50 posts with each post's author become, on a naive server, 1 query for the posts plus 50 more, one per author. The GraphQL documentation itself describes the case. REST has it too, but it shows up in the client, which makes one request per item.

The standard fix is DataLoader: it collects the ids requested during execution and calls a batch function once.

js
// npm install dataloader pg
import DataLoader from "dataloader";
import pg from "pg";

const db = new pg.Pool({ connectionString: process.env.DATABASE_URL });

// create new loaders for every request: DataLoader's cache is per request
export function createLoaders() {
  return {
    author: new DataLoader(async (ids) => {
      const { rows } = await db.query(
        "SELECT id, name FROM authors WHERE id = ANY($1)",
        [ids],
      );
      const byId = new Map(rows.map((author) => [author.id, author]));
      // the result must have the same length and order as the ids
      return ids.map((id) => byId.get(id) ?? null);
    }),
  };
}

// in the resolver: Post.author = (post, _args, ctx) => ctx.loaders.author.load(post.authorId)

The flip side of flexibility is cost. With REST, you know how heavy each route is and apply rate limiting per request. With GraphQL, a single request can ask for lists inside lists inside lists. The GraphQL documentation recommends paginating list fields, limiting query depth and breadth, and analyzing complexity before execution. GitHub's GraphQL API is a public example: each query costs points calculated from the connections it requests, every connection requires first or last, and queries over a node limit are rejected.

In both models, a batch query is only cheap if the filtered column has an index.

How does each one handle errors and versions?#

REST uses HTTP status codes: 404 for a missing resource, 422 for invalid data, 500 for a server failure. Proxies, monitors and HTTP clients understand these codes without knowing anything about your API. For the error body, RFC 9457 defines a standard format, application/problem+json.

GraphQL separates two kinds of error. Request errors (invalid syntax, a field that doesn't exist) happen before execution and carry no data; servers typically answer 400 for them. Field errors happen during execution and produce a partial response: the failed field becomes null (or its nearest nullable parent does) and the failure goes into errors. Since HTTP has no status code for partial success, the GraphQL documentation says to answer with a 2xx whenever data is not null:

json
{
  "data": { "user": { "name": "Ana", "orders": null } },
  "errors": [
    { "message": "Orders service unavailable", "path": ["user", "orders"] }
  ]
}

A monitor that only counts 5xx responses won't see that failure. Log the contents of errors on the server and handle them in the client.

On versions, the difference is cultural. In REST, a breaking change usually becomes a new version (/v2/orders), and both run until clients migrate. GraphQL takes a strong stance against versioning: since the client only gets what it asks for, new fields break nobody, and an old field gets the @deprecated directive, which tools show as a warning, until it falls out of use. Removing a field still breaks whoever requests it, so a schema needs discipline too.

When should you choose REST or GraphQL?#

Scenario Usually fits better
Public API for third parties, with documentation and CDN caching REST
Simple CRUD, few clients, small team REST
Webhooks, file upload and download REST
Several apps (web, mobile) asking for different combinations of the same data GraphQL
A layer that brings several services or databases together GraphQL
Screens with deeply nested data (user, orders, items, reviews) GraphQL

There is no universal winner, and it doesn't have to be one or the other. Many teams keep REST for public endpoints and integrations, and run GraphQL for their own apps. The team matters most: GraphQL asks for a schema, DataLoader, cost limits and a different kind of monitoring; REST asks for route discipline, documentation and versioning.

If you pick REST, describe the API with OpenAPI to get generated types and clients, which removes one of GraphQL's advantages. To pick a framework, see which Node.js framework to use.

How to do this on Square Cloud#

For hosting, REST and GraphQL are the same thing: an always-on HTTP process. On Square Cloud, your API runs as a web application in an isolated container, with no cold start and no sleeping on inactivity, and gets a *.squareweb.app subdomain with HTTPS on every plan. Listen on 0.0.0.0 on the port in the PORT variable. You can use Node.js, Python, Go and other runtimes.

The CDN respects the Cache-Control your application sends, so your code decides what gets cached. The proxy doesn't cut long-lived connections, and WebSocket and SSE pass through without buffering, which are the two usual transports for GraphQL subscriptions. The dashboard's real-time logs show whatever you log about the errors field.

With more than one application on the same custom domain, load balancing (from the Standard plan) spreads requests round-robin, without sticky sessions, so keep state in a database or Redis. The Hobby plan starts at R$12.49 per month with 1 GB of RAM, shared across your applications. For the step by step, see how to host an API, and the API hosting page sums up runtimes, plans and limits.

API hosting

APIs in always-on containers, with no cold starts

API hosting

FAQs

Is GraphQL faster than REST?

Not inherently. GraphQL cuts round trips when a screen needs data from several resources, but a naive resolver can fire dozens of database queries. Speed depends on the implementation and on caching.

Does GraphQL replace REST?

No. The two often live side by side in the same company: a public REST API for third parties and a GraphQL endpoint for the company's own apps, with webhooks and uploads on REST routes next to it.

Why does my GraphQL API return 200 with an error?

Because a GraphQL response can be partial: some fields resolved and some failed. When data is not null, the GraphQL documentation says to answer with a 2xx and list the failures in errors, so the client has to read the body, not only the status.

Can I cache GraphQL on a CDN?

Yes, with extra work. Queries sent over GET, ideally as persisted queries (a hash instead of the query text), can be cached when the server sends cache headers. Common HTTP caches don't reuse responses to POST.

Do I need to version a GraphQL API?

The recommended practice is a versionless schema that evolves: add new fields and mark old ones with @deprecated until nobody uses them. Removing a field still breaks clients that request it.

Next articleHow to host a FastAPI, Flask or Django appTo host a FastAPI, Flask or Django app, run it with a production server (Uvicorn or Gunicorn) on 0.0.0.0. Commands, Django settings and common errors included.