GraphQL Arguments in Queries
Arguments let you pass data into a query to filter, sort, or customize the result. Without arguments, every call to the same field returns the same data. Arguments make queries dynamic and precise.
Arguments Are Like Function Parameters
Think of a GraphQL field as a function. The field name is the function name, and arguments are the values you pass into it. The resolver uses those values to decide what to return.
Schema: Client passes:
──────── ──────────────
type Query {
employee(id: ID!): Employee employee(id: "7")
weather(city: String!): Data weather(city: "Delhi")
}
Fetching a Record by ID
The most common use of arguments is fetching a specific record by its unique ID.
Schema:
────────
type Product {
id: ID!
name: String!
price: Float!
}
type Query {
product(id: ID!): Product
}
Query:
───────
{
product(id: "101") {
name
price
}
}
Response:
──────────
{
"data": {
"product": {
"name": "Wireless Mouse",
"price": 24.99
}
}
}
Arguments for Filtering Lists
Arguments also filter lists. Instead of fetching all products and filtering in the app, you let the server filter for you.
Schema:
────────
type Query {
products(category: String, inStock: Boolean): [Product]
}
Query — only electronics that are in stock:
────────────────────────────────────────────
{
products(category: "electronics", inStock: true) {
name
price
}
}
Arguments for Sorting
Schema:
────────
enum SortOrder { PRICE_ASC PRICE_DESC NAME_ASC }
type Query {
products(sort: SortOrder): [Product]
}
Query:
───────
{
products(sort: PRICE_ASC) {
name
price
}
}
Arguments on Nested Fields Too
Arguments are not limited to the top-level fields in Query. Any field anywhere in the schema can accept arguments, including nested fields.
Schema:
────────
type Author {
name: String!
books(limit: Int): [Book] ← nested field with argument
}
Query:
───────
{
author(id: "5") {
name
books(limit: 3) { ← only the first 3 books
title
}
}
}
Required vs Optional Arguments
An argument followed by ! is required. Without it, the server rejects the query before running any resolver. An argument without ! is optional, and you can provide a default value.
type Query {
product(id: ID!): Product ← id is required
products(limit: Int = 10): [Product] ← limit is optional, defaults to 10
search(term: String!): [Product] ← term is required
}
✓ Valid: ✗ Missing required argument:
──────── ────────────────────────────
product(id: "5") {...} product {...} ← Error
Argument Types Match the Schema
GraphQL validates argument types at query execution time. Passing a string where an integer is expected causes a validation error before any resolver runs.
Schema says: products(limit: Int) ✓ Valid: products(limit: 5) ✗ Invalid: products(limit: "five") ← Type mismatch error
