GraphQL: Ask for Exactly What You Need
GraphQL lets clients request exactly the data they need from a single endpoint, avoiding over-fetching. It's ideal for mobile apps, but beware of the N+1 problem where one query can trigger many database lookups on the backend.
WHY IT EXISTS Traditional REST APIs often force clients into multiple round trips to fetch related data, or they return massive, fixed payloads with data the client doesn't need. This leads to over-fetching (wasting bandwidth) and under-fetching (requiring more calls). GraphQL was invented to give client applications the power to request exactly the data they need in a single call.
THE MENTAL MODEL GraphQL is a query language for your API, not a database. Imagine it as a smart waiter for your data. With REST, you order pre-defined dishes from a menu (e.g., /users/123, /users/123/posts). With GraphQL, you give the waiter a precise, custom order: "I want the user's name, the titles of their last three posts, and the first comment on each post." The waiter returns with exactly that, all on one plate.
HOW IT WORKS A client, like a React Native app, sends a query string to a single GraphQL endpoint. This query describes the desired data structure. The server has a strongly-typed schema that defines all possible data and operations. The server validates the query against this schema, then uses 'resolver' functions to fetch the requested data from various sources (databases, microservices, etc.). Finally, it returns a JSON object that mirrors the shape of the original query. The main operations are Queries (reading data), Mutations (writing data), and Subscriptions (real-time updates).
WHEN TO USE IT Use GraphQL when you have diverse clients with different data needs, such as a web app and a mobile app sharing one backend. It excels in complex systems with interconnected data, like social graphs or e-commerce platforms. It is particularly effective for mobile applications where minimizing network requests and data payload size is critical.
WHEN NOT TO USE IT For very simple APIs with only a few, fixed data resources, GraphQL can be overkill. If your application is a straightforward CRUD app that maps directly to database tables, the simplicity of REST might be a better fit. GraphQL adds complexity on the server side, requiring careful schema design and performance tuning of resolvers.
ONE CANONICAL EXAMPLE A React Native app needs to display a user's name and the titles of their 5 most recent posts. Instead of hitting /api/users/123 and then /api/users/123/posts, the client sends a single GraphQL query: query { user(id: "123") { name, posts(last: 5) { title } } }. The server responds with a single JSON object containing only the requested name and post titles, saving a network round trip and bandwidth.
Read the original → apollographql.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.