TExcelTAD
Home › GraphQL › Arguments

Arguments

In REST you pass parameters in the URL (/books?genre=scifi). In GraphQL every field can take arguments, not only the top-level ones. That means you can filter a list, format a value or pick a unit right where the field is selected.

Declaring and using arguments

Arguments are declared in the schema in parentheses after the field name, each with a type. A ! means the argument is required:

js · try it yourself
import { graphql, buildSchema } from 'graphql';

const schema = buildSchema(`
  type Book { id: ID, title: String }
  type Query {
    book(id: ID!): Book
    search(text: String!, limit: Int = 2): [Book]
  }
`);

const books = [
  { id: '1', title: 'The Hobbit' },
  { id: '2', title: 'The Silmarillion' },
  { id: '3', title: 'The Road' },
  { id: '4', title: 'Beloved' },
];

const rootValue = {
  // Root resolvers receive the arguments as their first parameter.
  book: ({ id }) => books.find((b) => b.id === id),
  search: ({ text, limit }) =>
    books.filter((b) => b.title.includes(text)).slice(0, limit),
};

const query = `{
  book(id: "4") { title }
  search(text: "The") { title }
}`;

const result = await graphql({ schema, source: query, rootValue });
console.log(JSON.stringify(result, null, 2));
{
  "data": {
    "book": {
      "title": "Beloved"
    },
    "search": [
      {
        "title": "The Hobbit"
      },
      {
        "title": "The Silmarillion"
      }
    ]
  }
}

limit: Int = 2 gives the argument a default value, so the query could leave it out and still got two results. Arguments are passed by name, so their order in the query doesn't matter.

Arguments on nested fields

Here is where GraphQL differs from REST: arguments work at any depth. Below, price takes a currency and reviews takes a minStars filter. When a field lives on an object (not on Query), its resolver method receives the arguments the same way:

js · try it yourself
import { graphql, buildSchema } from 'graphql';

const schema = buildSchema(`
  type Review { stars: Int, text: String }
  type Product {
    name: String
    price(currency: String = "USD"): Float
    reviews(minStars: Int = 1): [Review]
  }
  type Query { product: Product }
`);

const rates = { USD: 1, EUR: 0.9, JPY: 150 };

const product = {
  name: 'Desk lamp',
  priceUsd: 40,
  allReviews: [
    { stars: 5, text: 'Bright and sturdy' },
    { stars: 2, text: 'Cable too short' },
    { stars: 4, text: 'Nice design' },
  ],
  price({ currency }) {
    return this.priceUsd * rates[currency];
  },
  reviews({ minStars }) {
    return this.allReviews.filter((r) => r.stars >= minStars);
  },
};

const query = `{
  product {
    name
    price(currency: "EUR")
    reviews(minStars: 4) { stars text }
  }
}`;

const result = await graphql({ schema, source: query, rootValue: { product } });
console.log(JSON.stringify(result.data, null, 2));
{
  "product": {
    "name": "Desk lamp",
    "price": 36,
    "reviews": [
      {
        "stars": 5,
        "text": "Bright and sturdy"
      },
      {
        "stars": 4,
        "text": "Nice design"
      }
    ]
  }
}

Argument types are checked

Arguments are validated against the schema before anything runs. A missing required argument or a value of the wrong type is rejected with a clear message:

js · try it yourself
import { graphql, buildSchema } from 'graphql';

const schema = buildSchema(`
  type Query { book(id: ID!): String, top(limit: Int): [String] }
`);

for (const source of ['{ book }', '{ top(limit: "five") }', '{ top(count: 3) }']) {
  const result = await graphql({ schema, source, rootValue: {} });
  console.log(result.errors[0].message);
}
Field "book" argument "id" of type "ID!" is required, but it was not provided.
Int cannot represent non-integer value: "five"
Unknown argument "count" on field "Query.top".

Literal syntax

Type Literal in a query
String, ID "double quotes" (single quotes are not allowed)
Int, Float 42, -3, 9.99
Boolean true, false
null null
list [1, 2, 3]
enum ASC (a bare name, no quotes)
input object { title: "Hi", tags: ["a"] }

ID is a special case: in queries you may write it as a string or an integer (book(id: 4) also works), and resolvers always receive a string.

Tip: Hard-coding values inside the query string, like book(id: "4"), is fine for learning. Real apps use variables instead (a later lesson), so the query text stays constant and values are sent separately.

Test yourself

What does the ! in book(id: ID!) mean?

  1. The argument is optional
  2. The argument is required
  3. The argument is deprecated
  4. The argument is a list

Which fields can take arguments in GraphQL?

  1. Only fields of Query
  2. Only fields returning lists
  3. Any field
  4. Only mutation fields

Which string literal is valid in a GraphQL query?

  1. 'Dune'
  2. "Dune"
  3. ` Dune `
  4. Dune