API Design: REST vs GraphQL
The REST Philosophy: Resource-Based Architecture
REST (Representational State Transfer) has been the undisputed king of web APIs for two decades. It is built entirely around the concept of "Resources" and leverages standard HTTP verbs.
If you want to interact with a User, you use the /users endpoint. To get a specific user, you use GET /users/123. To delete them, you use DELETE /users/123. It is incredibly intuitive and perfectly utilizes the foundational architecture of the internet.
The Pros of REST: Because it relies on standard HTTP GET requests, it is infinitely cacheable. CDNs like Cloudflare can cache your GET /articles/5 response on servers across the globe, meaning your actual database never gets hit.
The Cons of REST: It suffers heavily from Over-fetching and Under-fetching. If your mobile app only needs a user's name, hitting /users/123 will still download their entire profile (Over-fetching). If you also need their 10 recent posts, you have to make a second network request to /users/123/posts (Under-fetching).
The GraphQL Philosophy: The Client Dictates
GraphQL, invented by Facebook, completely flips the REST model. Instead of having 50 different endpoints for 50 different resources, a GraphQL API has exactly one endpoint (usually POST /graphql).
Instead of the server deciding what data to send, the client sends a highly specific query string declaring exactly what it wants, and the server responds with a JSON object that perfectly matches that shape.
query {
user(id: 123) {
firstName
lastName
recentPosts(limit: 3) {
title
likes
}
}
}
The Pros of GraphQL: It completely eliminates over-fetching and under-fetching. The frontend gets exactly what it needs in a single network request, making it the ultimate tool for complex, data-heavy mobile applications and massive dashboards.
The Cons of GraphQL: It is terrible for HTTP caching, because every request is a unique POST request. Furthermore, if you do not carefully optimize your backend resolvers with DataLoaders, a deeply nested GraphQL query can trigger thousands of database queries, causing the infamous N+1 performance catastrophe.