tezvyn:

GraphQL Queries: Ask for Exactly What You Need

AI-drafted, machine-checkedSource: graphql.orgintermediate

GraphQL lets clients ask for exactly the data they need in a single call, like a flexible SQL query for your API. It avoids the over-fetching of fixed REST endpoints, making apps faster. The footgun: complex client queries can overload your server.

WHY IT EXISTS Traditional REST APIs have fixed endpoints. If a client needs just a user's name but the /user endpoint returns 50 fields, it's over-fetching. If it needs a user and their posts, it might require two separate API calls. GraphQL was created to give the client control, solving both problems with a single, flexible request.

THE MENTAL MODEL Think of your API as a graph of connected data. Instead of hitting multiple REST endpoints to walk that graph (e.g., /users/123, then /posts?userId=123), GraphQL gives you one smart endpoint. You send a single query describing the exact path through the graph and the fields you want to collect, and the server returns exactly that data in one trip.

HOW IT WORKS A GraphQL server defines a schema that describes all available data and its relationships using a strong type system. A client sends a query specifying the exact fields it wants, including nested objects. The server validates this query against the schema, runs functions called 'resolvers' to fetch the data from any backend source, and assembles a JSON response that precisely matches the structure of the query.

WHEN TO USE IT Use GraphQL when building clients with diverse data requirements, like mobile and web apps sharing a backend. It excels in microservice architectures, acting as a gateway that unifies many downstream services into a single API. It's ideal when network performance and minimizing data payloads are critical.

WHEN NOT TO USE IT For simple APIs with a few, non-nested resources, GraphQL can be overkill; a standard REST endpoint is simpler. Caching is also more complex. With REST, you can cache responses per URL. With GraphQL's single endpoint, you need more sophisticated client-side or server-side caching strategies.

ONE CANONICAL EXAMPLE A client needs a project's tagline and the names of its contributors. Instead of a call to /projects/graphql and another to /projects/graphql/contributors, it sends one GraphQL query: query { project(name: "GraphQL") { tagline, contributors { name } } }. The server responds with a single JSON object containing only the requested fields, avoiding over-fetching and a second network request.

Read the original → graphql.org

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.