GraphQL is another way of designing APIs. Instead of many addresses, there is usually a single entry point, and the client writes in its request exactly what data it needs. The server returns just that, no more and no less.
An example#
Suppose that on a profile page you only want the user's name and photo:
{
user(id: 12) {
name
avatar
}
}The JSON response contains only name and avatar. If you solved the same need with REST, a fixed response might include dozens of unnecessary fields.
Advantages#
- It avoids fetching extra data, which helps on mobile and weak connections
- You can get information from several related resources in one request
- The data structure is documented in a "schema", and tools can offer auto-completion from it
- The front end can change its needs without a new route being built in the back end
Disadvantages#
- Server-side implementation is more complex than simple REST
- Caching responses is harder
- Without limits, very heavy queries can put pressure on the server
Where you run into it#
Some large services and some WordPress plugins (such as headless WordPress tools) provide a GraphQL endpoint.
Choosing between REST and GraphQL#
For simple, small projects REST is usually enough and simpler. GraphQL becomes valuable when several clients with different needs want complex, related data.