Arguments, aliases and variables

GraphQL Course · lesson 3 of 14 · 5 min read

Parameterise a query properly, and fetch the same field twice in one request.

Open this lesson in the learning hub

Key points

  • Any field can take arguments: orders(status: SHIPPED, first: 5).
  • Never build a query by string concatenation - use variables, declared with $name.
  • Variables keep the query text constant, which lets the server cache the parsed document.
  • An alias renames a field in the response, which is how you request one field twice with different arguments.
  • Fragments factor out a repeated selection set so it is written once.

Example

query GetCustomer($id: ID!, $limit: Int = 10) {
  shipped: customer(id: $id) {
    ...basics
    orders(status: SHIPPED, first: $limit) { product }
  }
  pending: customer(id: $id) {
    orders(status: PENDING, first: $limit) { product }
  }
}

fragment basics on Customer { id name city }

# variables: { "id": "1", "limit": 5 }

Variables keep the query text stable; aliases let you ask for the same field twice.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the GraphQL Course course, and every lesson in it is listed on the GraphQL Course contents page.