REST, GraphQL & gRPC
Web API styles compared — REST resources, methods and status codes, HATEOAS and maturity levels, GraphQL schemas, queries, mutations and resolvers, the N+1 problem and DataLoader, gRPC and Protocol Buffers, plus OpenAPI and when to choose each.
Clients and servers need a contract for exchanging data. Three styles dominate: REST (resources over HTTP), GraphQL (a query language over one endpoint) and gRPC (typed remote procedure calls). Design principles common to all — versioning, pagination, idempotency — are covered in API design.
REST
REST (Representational State Transfer) models the API as resources identified by URLs, manipulated with standard HTTP methods (HTTP):
| Operation | Request | Success |
|---|---|---|
| List | GET /orders?status=open&limit=20 | 200 + array |
| Read | GET /orders/42 | 200, or 404 |
| Create | POST /orders + body | 201 + Location: /orders/43 |
| Replace | PUT /orders/42 + full body | 200 / 204 |
| Partial update | PATCH /orders/42 + changes | 200 |
| Delete | DELETE /orders/42 | 204 |
| Nested | GET /orders/42/items | 200 |
| Action | POST /orders/42/cancel | 200 / 202 |
Constraints that define REST: client–server, stateless requests (each carries all needed context, e.g. a token), cacheable responses (Cache-Control, ETag), uniform interface, layered system.
GET /orders/42 HTTP/1.1
Accept: application/json
Authorization: Bearer eyJ…
HTTP/1.1 200 OK
Content-Type: application/json
ETag: "a1b2c3"
Cache-Control: private, max-age=60
{"id": 42, "status": "shipped", "total": 4999, "customer": {"id": 7, "href": "/customers/7"}}Richardson maturity model: level 0 (one endpoint, RPC over HTTP) → 1 (resources) → 2 (HTTP verbs and status codes — where most "REST" APIs live) → 3 (HATEOAS: responses include links to possible next actions).
Strengths: simple, uses HTTP caching and tooling everywhere, easy to debug with curl. Weaknesses: over-fetching (getting fields you don't need), under-fetching (needing several round trips: user → orders → items), and endpoint sprawl for different clients.
OpenAPI
Describe REST APIs with an OpenAPI (formerly Swagger) spec to get documentation, client SDK generation, server stubs, mocking and contract tests:
paths:
/orders/{id}:
get:
parameters: [{ name: id, in: path, required: true, schema: { type: integer } }]
responses:
"200": { content: { application/json: { schema: { $ref: "#/components/schemas/Order" } } } }
"404": { description: Not found }GraphQL
GraphQL exposes a typed schema at a single endpoint; the client specifies exactly which fields it wants, across related objects, in one request.
type User {
id: ID!
name: String!
orders(last: Int = 10): [Order!]!
}
type Order { id: ID! total: Int! items: [Item!]! }
type Query { user(id: ID!): User }
type Mutation { cancelOrder(id: ID!): Order }
type Subscription { orderUpdated(userId: ID!): Order }query Dashboard {
user(id: "7") {
name
orders(last: 3) {
id
total
items { name }
}
}
}The response mirrors the query shape exactly — no over- or under-fetching, one round trip. The server implements resolvers, one function per field:
const resolvers = {
Query: { user: (_, { id }, ctx) => ctx.db.users.find(id) },
User: { orders: (user, { last }, ctx) => ctx.db.orders.byUser(user.id, last) },
Order: { items: (order, _, ctx) => ctx.loaders.itemsByOrder.load(order.id) },
};The N+1 problem and DataLoader
Naive resolvers fetch items separately for each order: 1 query for orders + N queries for items. DataLoader batches all load(id) calls within one tick into a single WHERE order_id IN (…) query and caches results per request.
GraphQL trade-offs
| Pros | Cons |
|---|---|
| Clients fetch exactly what they need; great for varied clients (web, mobile) | HTTP caching is harder (everything is POST /graphql); needs persisted queries or client caches (Apollo, Relay, urql) |
| Strongly typed schema, introspection, excellent tooling | Expensive queries are easy to write: need depth/complexity limits and timeouts |
| Evolve without versions (add fields, deprecate old ones) | More server complexity: resolvers, batching, authorisation per field |
| Federation composes many services into one graph | Errors return 200 with an errors array; monitoring per operation, not per URL |
gRPC
gRPC is a high-performance RPC framework: define services and messages in Protocol Buffers, generate client and server code in many languages, and communicate over HTTP/2 with compact binary encoding.
syntax = "proto3";
service OrderService {
rpc GetOrder(GetOrderRequest) returns (Order);
rpc ListOrders(ListOrdersRequest) returns (stream Order); // server streaming
rpc TrackOrders(stream TrackRequest) returns (stream OrderEvent); // bidirectional
}
message GetOrderRequest { int64 id = 1; }
message Order {
int64 id = 1;
string status = 2;
int64 total_cents = 3;
repeated Item items = 4;
}# Generated client stub
with grpc.insecure_channel("orders:50051") as ch:
stub = OrderServiceStub(ch)
order = stub.GetOrder(GetOrderRequest(id=42), timeout=0.5) # deadlineStrengths: small, fast binary messages; strict contracts with code generation; streaming in both directions; deadlines and cancellation built in. Weaknesses: not human-readable, limited direct browser support (needs gRPC-Web or Connect), and it requires schema tooling. Field numbers, not names, identify fields on the wire — never reuse a number.
Choosing
| Situation | Choose |
|---|---|
| Public API for third parties, broad compatibility | REST + OpenAPI |
| Multiple front ends with different data needs, complex relationships | GraphQL (often as a gateway / BFF over services) |
| Internal service-to-service calls, low latency, streaming, polyglot | gRPC |
| Real-time updates to browsers | WebSockets / SSE (Real-time), or GraphQL subscriptions |
| Simple CRUD inside one team | REST, or typed RPC (tRPC, server actions) |
- REST: resources + HTTP methods + status codes; stateless and cacheable; risks over- and under-fetching.
- OpenAPI specs give docs, SDKs and contract tests for REST.
- GraphQL: one endpoint, typed schema, clients choose fields; needs DataLoader batching and query-cost limits; HTTP caching is harder.
- gRPC: Protocol Buffers over HTTP/2, generated stubs, streaming and deadlines; ideal between services.
- Choose REST for public APIs, GraphQL for flexible client needs, gRPC for internal high-performance calls.
QWhat problems does GraphQL solve compared with REST, and what does it cost?medium
It removes over-fetching and under-fetching: clients request exactly the fields they need across related objects in one round trip, and a typed schema supports tooling and evolution without versioned endpoints. The costs: HTTP caching no longer works per URL, servers must guard against expensive queries with depth or complexity limits, resolvers need batching (DataLoader) to avoid N+1 queries, authorisation must be enforced per field, and monitoring is per operation rather than per endpoint.