Writing GraphQL Queries
A GraphQL query describes the data the client wants to read.
Suppose the schema contains:
type Query {
user(id: ID!): User
}
type User {
id: ID!
name: String!
email: String!
}
A client can request:
query {
user(id: "42") {
id
name
email
}
}
The fields selected inside user form a selection set.
GraphQL requires a selection set when a field returns an object type because the client must specify which fields of that object it wants.
For example, this is incomplete:
query {
user(id: "42")
}
if user returns User, because User is an object type rather than a scalar.
However, a scalar field does not need nested fields:
query {
user(id: "42") {
name
}
}
Queries can be named:
query GetUser {
user(id: "42") {
id
name
}
}
Naming operations becomes particularly useful for debugging, monitoring, persisted operations, and applications containing multiple operations.
query GetUserProfile {
user(id: "42") {
id
name
email
}
}The operation is named GetUserProfile. The user field returns an object, so a selection set is required. The selected scalar fields are returned in the same nested structure requested by the operation.
A query describes data that should be read.
Object fields require selection sets.
Scalar fields are leaf fields and do not require nested selections.
Named operations improve observability and maintainability.
Why does a GraphQL object field normally require a selection set?