Operation Names
At 2 a.m. the bookshop's error dashboard fills with "slow GraphQL request". Every entry says query, and nothing else. Which screen sent it? If every operation had a name, the dashboard would say BookPage or AddReview and you would know where to look.
The rule
Name every operation: required with several, priceless in logs.
An operation name goes right after the operation type:
query BookPage($id: ID!) {
book(id: $id) { title price }
}
mutation AddReview($input: AddReviewInput!) {
addReview(input: $input) { id }
}The rules:
- A document with exactly one operation may leave it anonymous, as in
query { ... }or the shorthand{ ... }. - A document with more than one operation must name all of them.
- Names must be unique within the document.
When a document holds several operations, the request says which to run in the operationName field of the JSON body:
{
"query": "query BookPage($id: ID!) { ... } query AuthorPage($id: ID!) { ... }",
"operationName": "BookPage",
"variables": { "id": "b1" }
}Even when a name is optional, write one. Server logs, tracing tools and client devtools show it, error reports group by it, and some tools use it to look up stored copies of the query. By convention names are PascalCase and describe the purpose or the screen: BookPage, BrowseFantasyShelf, UpdatePrice. A name like Query1 tells the 2 a.m. reader nothing.
The name is only a label for the operation. It does not change which fields run or the shape of data; the response keys still come from the fields and aliases.
The shortcut
Before sending any document, count the operations. One: a name is optional, but add one anyway. Two or more: every one needs a unique name, and the request needs operationName.
Count
The file holds
BookPageandAuthorPage. That is two.
The trap is thinking the name shows up in the response. It does not: data still starts with book.
Drills
Answer fast — trust the rule.
Is a document holding two anonymous queries valid?
A document contains BookPage and AuthorPage. How does the server know which to run?
Where does BookPage appear in the response to query BookPage { book(id: "b1") { title } }?
Which is the most useful operation name for the query behind the author screen?
Remember
- Name every operation: required with several, priceless in logs.
- Count the operations: several means unique names plus
operationNamein the request. - Trap: the name never appears in
data.
