Writing GraphQL Queries

1. Creating Basic Queries

FormExample
Shorthand{ me { id } } (anonymous query)
Namedquery GetMe { me { id } }
With variablesquery 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

PatternDetail
Object fieldOpen {}, select sub-fields
Scalar fieldNo selection set
Depth limitServer typically caps at 5–10 levels

4. Using Aliases

Example: Aliases for duplicate fields

{
  admin: user(id: "1") { name }
  guest: user(id: "2") { name }
}
UseReason
Same field, different argsAvoid response key conflict
Rename for clientMap 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 TypeForm
Scalar literalname: "Alice"
Enum literalrole: ADMIN
Variableid: $id
Input objectfilter: { active: true }
Listids: ["1", "2"]

7. Selecting Scalar Fields

TypeSelection
Scalar/EnumNo {} — leaf
Object/Interface/UnionRequired {} with sub-fields
List of scalarsNo {}

8. Selecting Object Fields

Example: Nested objects

{
  user(id: "1") {
    profile {
      avatar { url width height }
      address { city country }
    }
  }
}

9. Querying Lists

Example: List handling

{
  posts(first: 5) {
    id
    title
    tags
    author { name }
  }
}
BehaviorDetail
Selection applies per itemSame selection set replays for each list element
Order preservedServer 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

ReasonBenefit
Required for multi-op documentsServer uses operationName to pick
Tracing/LoggingIdentifies operation in logs/APM
Persisted queriesUsed as cache key