CodePark/ questions / GraphQL, gRPC & REST
START PRACTICINGPRACTICE
Backend question · HTTP & API design › GraphQL, gRPC & REST

Compare REST, GraphQL and gRPC. When would you pick each?

Pick REST for public and general APIs, GraphQL for varied frontends that need different data, and gRPC for fast service-to-service calls.

REST models resources at many URLs. It uses the standard HTTP methods and status codes. It works with every client, and it works well with HTTP caching and CDNs.
Its weaknesses:

  • Over-fetching: an endpoint returns more fields than the screen needs.
  • Under-fetching: an endpoint returns too little, so the client must call again.
  • Chatty clients: one screen needs several calls.

GraphQL has one endpoint and a typed schema. The client asks for exactly the fields it needs. Nested data comes back in one round trip. It suits varied frontends and mobile apps.
Its costs:

  • HTTP caching is harder.
  • There is a risk of N+1 queries: one query for a list, then one more query per item.
  • You must limit the cost and depth of queries.

gRPC sends Protocol Buffers (a compact binary format) over HTTP/2. You define the contract in .proto files, and tools generate the client code. It is compact and fast. It supports streaming in both directions, so it is good for calls between services. Browsers cannot call it directly. They need gRPC-Web and a proxy.

In short: a common mix is REST or GraphQL at the edge, for clients, and gRPC inside the system.

  • REST uses resources, works with every client and caches well, but can over-fetch or under-fetch.
  • GraphQL has one endpoint and client-shaped queries, but caching and N+1 queries are harder.
  • gRPC sends Protobuf over HTTP/2, generates code, supports streaming and suits internal services.
  • gRPC in browsers needs gRPC-Web.