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.

Intermediate 4 min readLesson 10 of 14 Interview Q&A

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):

OperationRequestSuccess
ListGET /orders?status=open&limit=20200 + array
ReadGET /orders/42200, or 404
CreatePOST /orders + body201 + Location: /orders/43
ReplacePUT /orders/42 + full body200 / 204
Partial updatePATCH /orders/42 + changes200
DeleteDELETE /orders/42204
NestedGET /orders/42/items200
ActionPOST /orders/42/cancel200 / 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.

HTTP
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:

YAML
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.

GraphQL
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 }
GraphQL
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:

TypeScript
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

ProsCons
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 toolingExpensive 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 graphErrors 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.

protobuf
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;
}
Python
# Generated client stub
with grpc.insecure_channel("orders:50051") as ch:
    stub = OrderServiceStub(ch)
    order = stub.GetOrder(GetOrderRequest(id=42), timeout=0.5)   # deadline

Strengths: 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

SituationChoose
Public API for third parties, broad compatibilityREST + OpenAPI
Multiple front ends with different data needs, complex relationshipsGraphQL (often as a gateway / BFF over services)
Internal service-to-service calls, low latency, streaming, polyglotgRPC
Real-time updates to browsersWebSockets / SSE (Real-time), or GraphQL subscriptions
Simple CRUD inside one teamREST, or typed RPC (tRPC, server actions)
Key takeaways
  • 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.
Interview questions
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.