BudiBadu Logo
Samplebadu

GraphQL by Example: Field Arguments

June 2018 Specification

Passing parameters to fields with this sample code demonstrating argument syntax using parentheses, filtering and modifying results with arguments, nested field arguments for granular control, and server-side transformations.

Code

query {
  # Pass an ID argument to the 'user' field
  user(id: "123") {
    name
    status
  }
  
  # Arguments can be passed to nested fields too
  posts(limit: 5) {
    title
    # Format the date on the server
    createdAt(format: "YYYY-MM-DD")
  }
}

Explanation

GraphQL fields and nested objects can accept arguments for filtering, pagination, or transforming results. Arguments are defined in the schema as either required or optional, enabling operations like fetching specific users by ID, paginating lists, or formatting dates server-side. This granular control surpasses REST query parameters by tying arguments to specific fields rather than entire endpoints.

Arguments are passed in parentheses () after field names using name-value pairs. The expression user(id: "123") tells the server to execute the user field resolver with the id argument set to "123", which the resolver uses to look up the correct user in the database. Multiple arguments can be passed to a single field, separated by commas.

This field-level argument system allows multiple independent queries in single requests using aliases, impossible with standard REST endpoints. For example, fetching user "123" and user "456" simultaneously by aliasing the user field twice with different arguments. Even scalar fields can accept arguments to transform output, as shown with createdAt(format: "YYYY-MM-DD") formatting dates on the server.

Code Breakdown

3
user(id: "123") named argument, schema defines argument type like String or ID.
9
posts(limit: 5) pagination argument limits returned results.
12
createdAt(format: "...") scalar field with argument for server-side transformation.
3-5
Argument passed to field, selection set specifies which user fields to return.