How to Pass Arguments in GraphQL Query: Simple Guide
In GraphQL, you pass arguments by specifying them inside parentheses after the field name in your query using
argumentName: value syntax. These arguments allow you to filter or customize the data returned by the query.Syntax
To pass arguments in a GraphQL query, write the field name followed by parentheses containing argumentName: value pairs. Values can be strings (in quotes), numbers, booleans, or variables. This tells the server what specific data you want.
- Field name: The data you want to fetch.
- Arguments: Parameters inside parentheses to filter or customize the data.
- Values: The actual data you pass, like a string or number.
graphql
query GetUser {
user(id: "123") {
name
email
}
}Example
This example shows a query that fetches a user by their id argument. The server returns the user's name and email. This demonstrates how to pass a string argument to get specific data.
graphql
query GetUserById {
user(id: "abc123") {
name
email
}
}Output
{
"data": {
"user": {
"name": "Alice",
"email": "alice@example.com"
}
}
}
Common Pitfalls
Common mistakes when passing arguments include:
- Forgetting to put string values in quotes, which causes syntax errors.
- Using incorrect argument names that the server does not recognize.
- Passing variables without declaring them in the query.
Always check the schema for correct argument names and types.
graphql
query WrongQuery {
user(id: abc123) { # Missing quotes around string value
name
}
}
# Corrected version:
query CorrectQuery {
user(id: "abc123") {
name
}
}Quick Reference
| Concept | Description | Example |
|---|---|---|
| Argument syntax | Use parentheses after field with name:value pairs | user(id: "123") |
| String values | Must be in double quotes | "abc123" |
| Number values | Use numbers directly | limit: 10 |
| Boolean values | Use true or false | active: true |
| Variables | Declare and pass with $ prefix | user(id: $userId) |
Key Takeaways
Pass arguments in GraphQL by adding parentheses with name:value pairs after the field.
Always put string argument values in double quotes to avoid syntax errors.
Check the GraphQL schema for correct argument names and types before querying.
Use variables for dynamic arguments by declaring them in the query.
Common errors include missing quotes and wrong argument names.