GraphQL schemas define the types, fields, and operations available in an API.
Now let's understand how clients actually interact with that schema.
GraphQL provides two primary operations for working with application data: queries and mutations.
Queries allow clients to retrieve information, while mutations allow them to create, update, or delete data.
Both use the same basic syntax, and both let clients specify which fields they want in the response.
However, there are important differences in their purpose, execution behavior, and design considerations.
In this chapter, we'll explore queries and mutations using our bookstore application, along with practical patterns for designing and consuming GraphQL APIs.
A query is a read operation that retrieves data from a GraphQL API.
Unlike REST, where clients typically access different resources through different URLs, GraphQL lets clients describe the data they want through a query document.
Suppose our schema defines:
A client can retrieve a book using:
The server responds with:
Notice that the response follows the structure of the query.
The client requested three fields, so the server returned those three fields.
This is called a selection set. It defines which fields should appear in the result.
If the client also needs the description, it can simply add that field to the query without requiring a new endpoint.
The server validates the requested fields against the schema before executing the query.
If the client requests a field that doesn't exist, GraphQL returns a validation error.
The flow below shows the two paths a query can take once it reaches the server.
Validation happens before any resolver runs. A query that asks for an unknown field never touches the database, and the client gets an error that names the problem.
GraphQL fields can accept arguments that control which data is returned.
For example:
The book field requires an ID, while books accepts an optional limit with a default value of 20.
Clients can use these arguments directly:
Arguments can also represent filtering, sorting, or search criteria.
Consider:
A client could now request:
This keeps related filtering options organized while making the API easier to extend.
Validate the limit argument on the server and cap it, so clients can't request excessively large collections.
Hardcoding argument values inside queries works for demonstrations, but real applications usually pass dynamic values.
GraphQL supports this through variables.
Instead of writing:
We can define a named query:
And send variables separately:
Here, $bookId is a variable of type ID!.
The same query can be reused with different book IDs without modifying its structure.
Variables provide several advantages.
They separate dynamic input from the query document, make queries easier to reuse, and allow GraphQL to validate input values against declared types.
They also work well with persisted queries and client-side tooling.
Most production GraphQL clients use variables rather than constructing query strings through manual string concatenation.
One of GraphQL's main benefits is the ability to retrieve related data within the same operation.
Suppose our schema contains:
A client can request:
The response might look like:
The frontend receives all the requested information in one GraphQL operation.
However, this doesn't mean the backend performs only one database query.
The server might still retrieve the book, author, and reviews separately.
Efficient resolver implementation is essential to prevent nested queries from creating performance problems.
Sometimes a client needs to request the same field multiple times with different arguments.
Consider retrieving two books:
Here, firstBook and secondBook are aliases.
The response uses those aliases as field names:
Without aliases, requesting the same field with conflicting arguments would create a validation conflict.
Aliases are useful when comparing resources, fetching multiple variations of the same data, or giving response fields more convenient names.
They change the response field names, not the underlying schema fields.
As applications grow, multiple queries often request the same groups of fields.
For example, several pages might display a book card containing its ID, title, and price.
Instead of repeating those selections, GraphQL provides fragments.
We can reuse the fragment in queries:
Or in another operation:
Fragments improve consistency and make large queries easier to maintain.
They are especially useful in frontend applications where multiple components depend on the same GraphQL types.
Fragments can also be defined inline when selecting fields for interfaces or union types.
Queries are designed for reading data. Mutations are designed for operations that change application state.
In REST, we commonly use POST, PUT, PATCH, and DELETE for write operations.
In GraphQL, these operations are exposed through fields on the Mutation type.
For example:
A client can execute:
With variables:
The server creates the book and returns the requested fields.
Unlike many REST APIs that return a fixed response body, GraphQL mutations allow clients to select which fields they need from the result.
This can eliminate the need for an immediate follow-up query.
Mutation names should describe meaningful actions.
For a bookstore, we might define:
Notice that publishBook represents a specific business action.
It communicates intent more clearly than requiring clients to update a generic status field.
This matters when operations involve business rules, permissions, or additional side effects.
For example, publishing a book might validate its metadata, update its availability, and notify subscribers.
Input objects are particularly useful for mutations because they group related parameters.
The client only supplies the fields it wants to modify.
However, update semantics must be clearly defined.
For nullable input fields, omitting a field and explicitly passing null are different actions.
For example, an omitted description could mean "leave unchanged," while an explicit null could mean "clear the description."
The server must handle this distinction consistently.
The decision below shows how the server can treat each of the three cases for description in UpdateBookInput.
The resolver has to check whether the key is present, not just whether its value is null. Treating omitted and null the same way would clear descriptions that the client never meant to touch.
Mutations should return meaningful information.
For example, returning the updated book allows clients to refresh their local state without making another request.
For more complex operations, a dedicated payload type can provide additional information:
The exact response structure depends on the application's requirements.
Mutations may also be retried after network failures, so important write operations should consider idempotency keys or other duplicate-prevention mechanisms.
Queries and mutations have an important execution difference.
GraphQL query fields are generally independent and may be resolved in parallel.
However, top-level mutation fields execute serially, in the order they appear.
For example:
The second top-level mutation executes after the first one finishes.
Top-level mutations run in order, but if the first succeeds and the second fails, GraphQL does not roll back the first. Applications that need atomic behavior must implement it in backend transactions or business logic.
The sequence below follows the two aliased publishBook mutations when the second one fails.
The server waits for first to finish before starting second, so the order is guaranteed. The failure of second does not undo first, which is why atomic behavior has to come from the backend.
Execution errors can arrive alongside partial data, even when the HTTP status is 200 OK, so clients should check both the data and errors fields of a response.
Queries and mutations are the primary ways clients interact with GraphQL APIs.
Queries retrieve data using flexible field selections, arguments, variables, aliases, and fragments.
Mutations represent operations that change application state and allow clients to request useful information from the result.
Although GraphQL simplifies how clients access data, backend concerns such as authorization, database efficiency, transaction management, and retries still need careful attention.
The key is to design queries around how clients consume data and mutations around meaningful business operations.
10 quizzes