GraphQL vs REST

GraphQL and REST can both be used to build production APIs, but they model API interaction differently.

In REST, the API is usually organized around resources and HTTP endpoints. In GraphQL, the API is organized around a typed schema and operations.

A REST API might expose:

GET    /users/42
GET    /users/42/posts
POST   /users
PATCH  /users/42
DELETE /users/42

A GraphQL API may expose a single endpoint such as /graphql, with operations represented in the schema:

query {
  user(id: "42") {
    name
    posts {
      title
    }
  }
}

GraphQL's single endpoint does not mean that GraphQL has only one operation. The schema can expose many query fields and mutation fields through that endpoint.

REST strengths

REST integrates naturally with HTTP semantics. HTTP caching, status codes, proxies, CDNs, and resource-oriented tooling are well understood.

GraphQL strengths

GraphQL provides a strongly typed schema, client-controlled selection sets, nested data fetching, introspection, and a unified API contract.

Important distinction

GraphQL does not eliminate HTTP. GraphQL is frequently transported over HTTP. It changes how API operations and response shapes are modeled rather than replacing the network itself.

REST and GraphQL
API structure: REST: resources/endpoints; GraphQL: schema/operations
REST commonly maps resources to URLs, while GraphQL exposes fields and operations through a schema.
Response shape: REST: server-defined representation; GraphQL: client selection
GraphQL lets the client select fields from the schema.
Transport: REST commonly uses HTTP; GraphQL commonly uses HTTP
GraphQL does not require a completely different network transport.
Do not think of GraphQL as REST with one endpoint

The most important difference is the API model. GraphQL exposes a typed graph of operations and fields rather than simply moving REST resources behind a single URL.

Key Takeaways
  • REST is resource-oriented while GraphQL is schema and operation-oriented.
  • GraphQL commonly uses one HTTP endpoint but can expose many operations.
  • GraphQL still commonly runs over HTTP.
  • Both approaches can be appropriate for production systems.
Knowledge Check

Which statement most accurately describes GraphQL compared with REST?