Writing GraphQL Queries
1. Creating Basic Queries
| Form | Example |
|---|---|
| Shorthand | { me { id } } (anonymous query) |
| Named | query GetMe { me { id } } |
| With variables | query U($id: ID!) { user(id: $id) { name } } |
2. Using Query Arguments
Example: Field arguments
{
user(id: "1") {
posts(first: 10, orderBy: { field: CREATED_AT, direction: DESC }) {
id
title
}
}
}
3. Nesting Query Fields
| Pattern | Detail |
|---|---|
| Object field | Open {}, select sub-fields |
| Scalar field | No selection set |
| Depth limit | Server typically caps at 5–10 levels |
4. Using Aliases
Example: Aliases for duplicate fields
{
admin: user(id: "1") { name }
guest: user(id: "2") { name }
}
| Use | Reason |
|---|---|
| Same field, different args | Avoid response key conflict |
| Rename for client | Map to JS property names |
5. Requesting Multiple Root Fields
Example: Single round-trip
query Dashboard {
me { id name }
notifications(unread: true) { id message }
feed(first: 20) { id title }
}
6. Using Field Arguments
| Argument Type | Form |
|---|---|
| Scalar literal | name: "Alice" |
| Enum literal | role: ADMIN |
| Variable | id: $id |
| Input object | filter: { active: true } |
| List | ids: ["1", "2"] |
7. Selecting Scalar Fields
| Type | Selection |
|---|---|
| Scalar/Enum | No {} — leaf |
| Object/Interface/Union | Required {} with sub-fields |
| List of scalars | No {} |
8. Selecting Object Fields
Example: Nested objects
{
user(id: "1") {
profile {
avatar { url width height }
address { city country }
}
}
}
9. Querying Lists
| Behavior | Detail |
|---|---|
| Selection applies per item | Same selection set replays for each list element |
| Order preserved | Server returns list in resolver order |
10. Using Query Variables
Example: Variables
query GetUser($id: ID!, $withPosts: Boolean = false) {
user(id: $id) {
name
posts @include(if: $withPosts) { id title }
}
}
11. Setting Query Operation Name
| Reason | Benefit |
|---|---|
| Required for multi-op documents | Server uses operationName to pick |
| Tracing/Logging | Identifies operation in logs/APM |
| Persisted queries | Used as cache key |