Glossary · Software Architecture

What is GraphQL?

Short answer

GraphQL is a query language and runtime for APIs, created at Facebook and open-sourced in 2015. Clients send a query describing exactly the fields they need, possibly across several related resources, and receive just that data in one response. The API is described by a typed schema, which enables tooling such as autocompletion and validation.

An example

A mobile app needs a customer’s name and their three latest orders with totals. With GraphQL it sends one request:

{ customer(id: 42) { name orders(last: 3) { number total } } }

and gets back exactly those fields. With a typical REST API that could take two or more requests, each returning fields the app doesn’t use.

GraphQL or REST?

  • GraphQL suits apps with many different screens or clients that need different slices of related data, and teams that want a strongly typed contract between front end and back end.
  • REST suits simple resource APIs, public APIs that benefit from HTTP caching, and file uploads or downloads.

Things to watch

  • Performance: nested queries can trigger the N+1 query problem; use batching (DataLoader) and limit query depth and complexity.
  • Caching: everything goes through one POST endpoint, so HTTP caching needs persisted queries or a GraphQL-aware cache.
  • Authorisation: check permissions per field and per object, not just per request.

In PHP, Lighthouse (Laravel) and API Platform or webonyx/graphql-php are the common choices.

Published · Updated · By · All terms

Go deeper