Computer Science and Software Engineering Comparison

GraphQL vs REST APIs Compared

GraphQL vs REST APIs Compared: featured diagram
Short answer

GraphQL vs REST compares two ways to build a web API. REST exposes many resource URLs, each returning a fixed representation through standard HTTP methods. GraphQL exposes one typed schema, usually at a single endpoint, where the client sends a query naming exactly the fields it wants and gets them back in one response.

GraphQL vs REST is a common design choice when a team builds the API behind a web or mobile app. REST is an architectural style that Roy Fielding described in his 2000 dissertation. GraphQL is a query language and runtime created at Facebook and released publicly in 2015, now maintained by the GraphQL Foundation.

Both normally run over HTTP and both usually return JSON. The difference is who decides the shape of the response: the server in REST, the client in GraphQL.

Watch: How GraphQL and REST work in 18 seconds

What REST and GraphQL mean

A REST API models the system as resources, each named by a URL such as /users/42. Clients act on them with HTTP methods: GET reads, POST creates, PUT replaces, PATCH updates part of a resource and DELETE removes it. Our REST API guide covers the basics.

Fielding defined REST by its constraints: client-server, stateless requests, cacheable responses, a uniform interface, a layered system and optional code on demand.

A GraphQL API is defined by a schema of types and fields. The client writes an operation, and the server runs a resolver function for each field it asks for. The specification defines three operation types: query (read), mutation (write) and subscription (a stream of results over time).

GraphQL vs REST comparison table

FeatureRESTGraphQL
EndpointsMany, one URL per resource or collectionUsually one, such as /graphql
Response shapeFixed by the server for each endpointChosen by the client, field by field
Fetching related dataOften several requestsNested fields in one request
ContractDocumentation or an OpenAPI descriptionStrongly typed schema, readable by introspection
HTTP methodsGET, POST, PUT, PATCH, DELETE with their meaningMostly POST, sometimes GET for queries
CachingStandard HTTP caching by URLMainly client side caches keyed by object ID
ErrorsHTTP status codes such as 404 or 500An errors list in the response, often with partial data
VersioningOften a version in the URL, such as /v2/Evolve one schema, mark old fields @deprecated
Real timeSeparate mechanism (polling, WebSockets)Subscription operation in the spec
RESTClientapp screenGET /users/42GET /users/42/postsGET /posts/7/comments3 requests,fixed responseshapesGraphQLClientapp screenqueryJSON dataPOST /graphqlone endpointusers resolverposts resolvercomments resolverteal: requestorange: response
REST spreads one screen’s data across several resource URLs, while GraphQL sends one query to a single endpoint whose resolvers gather the requested fields.
Download diagram (WebP)

GraphQL vs REST differences explained

Over-fetching and under-fetching

A REST endpoint returns the whole representation the server designed. If a list screen only needs a user’s name and photo, it still downloads every other field. That is over-fetching.

The opposite is under-fetching: one endpoint does not hold everything the screen needs, so the client makes more calls. GraphQL addresses both, because the query lists the exact fields, including nested related objects.

One request, one shape

A GraphQL query mirrors the shape of the JSON it returns. This query asks for a user, the titles of their latest posts and a comment count:

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

The response has a top level data object with the same nesting. If some fields fail, the specification lets the server return what it could resolve along with an errors list.

HTTP semantics and caching

REST uses HTTP the way RFC 9110 defines it. GET and HEAD are safe, and PUT and DELETE are idempotent, so repeating them has the same effect as sending them once. Status codes carry the result, and the transport itself is covered in how HTTP works.

RFC 9111 caching works on the request URL. A GET for /users/42 can be stored by the browser, a CDN or a proxy and reused until it expires.

GraphQL usually sends every operation as a POST to one URL, so shared HTTP caches cannot tell queries apart. The graphql.org guidance is to give each object a globally unique ID so that client libraries can keep a normalized cache keyed by that ID.

The N+1 problem on a GraphQL server

Each field has its own resolver. A naive server that resolves comments for each of 5 posts runs 1 query for the posts and then 5 more, one per post. The usual fix is batching: collect the IDs requested in one tick and load them in a single call, a pattern popularised by the DataLoader library listed on graphql.org.

Versioning and schema evolution

REST APIs often add /v2/ when a breaking change is needed and keep /v1/ running for old clients. GraphQL encourages one evolving schema instead. New fields are added freely, since old clients never ask for them, and old fields are marked with the @deprecated directive defined in the specification.

Fetching one screen: a worked example

Worked example
Given
A profile screen shows user 42, the user’s 5 latest posts and the comments under each post. Network round trip time is 80 ms. The REST API has /users/42, /users/42/posts and /posts/id/comments endpoints.
Find
The number of HTTP requests and the minimum network wait for REST and for GraphQL.
Assumptions
The REST client must read the user before the posts list and the posts list before the comment calls, but sends the 5 comment calls in parallel. Server processing time and bandwidth are ignored.
Solution
REST requests = 1 user + 1 posts list + 5 comment lists = 7 requests
REST sequential stages = user, then posts, then comments = 3 stages
REST network wait = 3 x 80 ms = 240 ms
GraphQL requests = 1 query with nested fields = 1 request
GraphQL network wait = 1 x 80 ms = 80 ms
Saving = 240 ms minus 80 ms = 160 ms, and 7 minus 1 = 6 fewer requests
Answer
REST needs 7 requests and about 240 ms of network wait; GraphQL needs 1 request and about 80 ms
Limitations
The GraphQL server still has to fetch the same data, so its own work does not disappear. A REST API can also offer a combined endpoint or embed related data, and HTTP caching can serve repeat REST reads with no round trip at all.

How a GraphQL request is handled

  1. The client sends an operation, usually as a POST with a JSON body holding the query text and any variables.
  2. The server parses the document and validates it against the schema, rejecting unknown fields or wrong argument types before running anything.
  3. Execution starts at the root type (Query, Mutation or Subscription) and calls the resolver for each requested field, working down the nesting.
  4. Resolved values are assembled into a data object that has the same shape as the query.
  5. The server returns the data, plus an errors list if any field could not be resolved.

When to use GraphQL or REST

  • Resources map cleanly to URLs and clients mostly read or write whole resources.
  • You want plain HTTP caching through browsers, CDNs and proxies.
  • The API is public and must be easy to call with any HTTP tool.
  • File uploads, downloads and simple CRUD services dominate.
  • Many different clients, such as web, iOS and Android, need different slices of the same data.
  • Screens combine data from several services or deeply related objects.
  • Slow or metered mobile networks make extra round trips and unused fields costly.
  • You want a typed schema that tools can introspect for autocompletion and validation.
  • Keep REST between internal services and add a GraphQL layer for front end clients.
  • Expose REST for public partners and GraphQL for your own apps.
  • The frontend and backend teams then agree on one schema for the user interface.

Common mistakes

  • Treating GraphQL as a database query language. It queries the API schema, and resolvers decide where data comes from.
  • Leaving queries unbounded. A deeply nested query can be expensive, so servers usually limit depth or cost.
  • Designing REST as remote procedure calls, such as /getUser or /deleteUser, instead of resources with HTTP methods.
  • Returning 200 for every REST error, which hides failures from caches, proxies and monitoring tools.

GraphQL vs REST interview and viva questions

  1. What is the main difference between GraphQL and REST? REST exposes many resource URLs with fixed responses, while GraphQL exposes one typed schema where the client chooses the exact fields it wants.
  2. What are over-fetching and under-fetching? Over-fetching is downloading fields the client does not use; under-fetching is needing extra requests because one endpoint does not return everything a screen needs.
  3. Name the three GraphQL operation types. Query for reading, mutation for writing and subscription for receiving results over time.
  4. Why is HTTP caching simpler with REST? REST reads are GET requests on distinct URLs, which RFC 9111 caches can store and reuse, while GraphQL usually sends every operation as a POST to one URL.
  5. What is the N+1 problem in GraphQL? Resolving a list field and then one extra data fetch per item, which batching techniques such as DataLoader reduce to a single call.

Frequently asked questions

Is GraphQL faster than REST?

Not by itself. GraphQL can cut the number of round trips and the amount of unused data a client downloads, which helps on slow mobile links. A well designed REST API with HTTP caching can be just as fast or faster for simple resource reads. Measure with your own screens and traffic.

Does GraphQL replace REST?

No. Both run over HTTP and many companies use both. A common pattern puts a GraphQL layer in front of existing REST services so that web and mobile clients get one flexible endpoint, while internal services keep talking REST.

Can a GraphQL API use HTTP GET?

Yes. Most servers accept queries by POST with a JSON body, and many also accept a query in the URL of a GET request. GET makes it easier to cache read queries in browsers and CDNs. Mutations should not be sent with GET because GET is meant to be a safe method.

References

  1. GraphQL Foundation, GraphQL Specification, October 2021 Edition, spec.graphql.org
  2. R. T. Fielding, Architectural Styles and the Design of Network-based Software Architectures, PhD dissertation, University of California, Irvine, 2000
  3. IETF RFC 9110, HTTP Semantics, R. Fielding, M. Nottingham and J. Reschke (eds.), June 2022
  4. IETF RFC 9111, HTTP Caching, R. Fielding, M. Nottingham and J. Reschke (eds.), June 2022
  5. GraphQL Foundation, Learn GraphQL: Introduction, Queries, Caching and Best Practices, graphql.org/learn
  6. L. Richardson, M. Amundsen and S. Ruby, RESTful Web APIs, O'Reilly Media, 2013

Get one engineering email a week

New articles, worked examples and study notes every week. Free, no spam, unsubscribe any time.

Sayali Ganjale
Author, Computer Science and AI, MCA, MIT World Peace University, Pune

MCA student at MIT World Peace University (MIT-WPU), Pune, focused on software development and problem solving. Works with Java, C, C++ and Python. Writes the Computer Science and AI and Data articles on Zenta Engineering. Editorial policy.

Related articles