Arguments in Queries
What you'll learn: How to pass arguments to GraphQL fields to filter, sort, or customize the data returned by your queries.
Why Arguments Matter
In GraphQL, you're rarely interested in all the data a server has to offer. Maybe you want a specific user, posts from the last week, or products sorted by price. Arguments let you tell the server exactly what you need, making your queries precise and efficient.
How Arguments Work
Arguments in GraphQL work like function parameters. You add them in parentheses after a field name, passing key-value pairs that the server uses to customize its response.
Think of it like ordering at a restaurant: instead of saying "I want pasta," you say "I want pasta (size: large, sauce: marinara, spicy: true)." The kitchen (server) uses those details to prepare exactly what you want.
Basic Syntax
query {
user(id: "123") {
name
email
}
}
Here, id: "123" is an argument that tells the server which user you want.
Multiple Arguments
You can pass several arguments to the same field:
query {
posts(limit: 10, sortBy: "createdAt", order: "DESC") {
title
author
}
}
This asks for 10 posts, sorted by creation date in descending order.
Arguments at Different Levels
Different fields in your query can have their own arguments:
query {
user(id: "123") {
name
posts(status: "published") {
title
}
}
}
The outer id filters which user, while the inner status filters which posts to include.
Key Takeaway: Arguments transform GraphQL queries from generic data requests into precise, customized instructions that fetch exactly the data you need, reducing over-fetching and improving performance.