With GraphQL, there is typically only one endpoint. Instead of several fixed REST routes, the client sends a query that describes exactly the fields it wants, and gets back a response in the same structure. As a result, it fetches neither too much nor too little data, and can traverse nested, related objects in a single request instead of making multiple roundtrips as in the classic REST approach.
The foundation is a strong type system: the schema is described in the Schema Definition Language (SDL) and defines which types, fields, and arguments exist. Every field can have its own arguments, and the response always has the same shape as the request. Results sit under a data key, errors under errors.
GraphQL has three operation types:
- Query: read data.
- Mutation: write data, i.e. create, change, or delete.
- Subscription: real-time data, the server pushes updates to the client.
Practical building blocks include variables (dynamic values with $name instead of string interpolation), named operations for better logging and debugging, and fragments to reuse recurring sets of fields.
Advantages:
- High flexibility, the client determines the fields.
- Nested data in a single request instead of many roundtrips.
- Schema and type system serve as a contract and enable validation as well as introspection.
Drawbacks and pitfalls:
- Caching is harder than with REST, because usually a single endpoint is used via POST instead of many cacheable URLs.
- More complexity on the server side, for example through resolvers, per-field authorization, and schema maintenance.
- The N+1 problem: nested fields can trigger many individual queries, which makes batching and caching (for example dataloaders) necessary.
Typical use: data-hungry frontends and mobile apps that want to efficiently load a lot of related data, as well as scenarios where many different clients need their own views of the same data.
query HeroNameAndFriends($episode: Episode = JEDI) {
hero(episode: $episode) {
name
friends {
name
}
}
}A query with a variable and nested fields: a hero and the names of their friends are loaded in a single request. The default JEDI allows the call even without a passed variable.
Sources
- Learn GraphQL GraphQL Foundation (graphql.org)
- Queries GraphQL Foundation (graphql.org)