GraphQL by Example: Nested Field Selection
Traversing object relationships with this code example showing selection sets for nested objects, hierarchical data fetching in single requests, avoiding under-fetching with related data, and client-driven data requirements.
Code
query {
# Fetch the 'me' object
me {
# Select specific fields from 'me'
name
email
# Nested object selection
address {
city
country
}
}
}Explanation
GraphQL's ability to handle nested objects and relationships enables fetching deeply nested data in single requests, eliminating multiple round trips required in REST architectures. Selection sets define the exact structure of data clients expect to receive, with curly braces opening a selection set specifying which fields to retrieve from returned objects. This hierarchical querying directly addresses under-fetching by allowing clients to gather all necessary related data in one operation.
Selection set characteristics include:
- Every field returning an object type must have a selection set
- Scalar types like String or Int do not require selection sets
- Selection sets give GraphQL its recursive nature for nested data fetching
- Clients can traverse related objects and their fields within single queries
- Response JSON structure matches the hierarchical selection exactly
In this example, requesting the me field returns a User object, with the selection set specifying only name, email, and address fields. The address field itself returns an Address object requiring its own selection set for city and country. This client-driven approach means frontend developers can change data requirements without backend API endpoint modifications.
Code Breakdown
me { ... } indicates me returns object, requires selection set of sub-fields.name and email scalar fields, no selection sets needed.address { ... } nested selection, can nest as deep as schema allows.
