Designing a GraphQL API

For the registrar’s REST API, your job as a designer was to decide the resources, the endpoint for each one, what a request and a response look like, and how the API performs under load and over time. A GraphQL API needs the same kind of decisions. Most of them match a REST decision. A few are no longer needed, and a few are new.

  • Types instead of resources. When designing the REST API for the registrar, you decided which resources the API exposes. In GraphQL, you decide which types the API has. For the shop, the types are the product, the cart, the cart item, the order, and the order item.

  • Entry points instead of endpoints. There is one URL, so there are no paths to decide. Instead you decide which fields a query may start from, and what arguments each one takes. In the cart page query, cart is an entry point and id is its argument. A filter that would be a query parameter in REST is an argument here.

  • Fields instead of a fixed response. When designing the REST API, you decided the representation of each resource, and every client received the same one. In GraphQL you decide which fields each type has, the type of each field, and whether a field can be null. The client decides which of those fields it receives. You also decide the error codes, but not a status code for each error.

  • Mutations for writes. In REST a write is a method on a resource, such as POST /orders. In GraphQL every request is a POST, and the body says whether it reads or writes. A request that reads is a query. A request that writes is a mutation. You name each mutation, decide its arguments, and decide what it returns.

  • Load and change over time. Lists still need pagination. Caching, rate limiting, and versioning need different answers than in REST, because every request has the same URL and the same method. Documentation is mostly the types and fields you declared, plus a description you can write on each one.

  • New decisions. You also decide how deeply a query may nest and how much work one query may ask for.

In GraphQL, you write the types, entry points, fields, and mutations in one document called the schema.