How to Write Query in GraphQL: Syntax and Examples
To write a query in
GraphQL, use the query keyword followed by the fields you want to fetch inside curly braces. Each field represents data you want from the server, and you can nest fields to get related data in one request.Syntax
A GraphQL query starts with the query keyword (optional if unnamed), followed by curly braces { } enclosing the fields you want to retrieve. Fields can be nested to fetch related data. You can also pass arguments to fields to filter or customize the data.
- query: keyword to start a query (optional if unnamed)
- { }: braces to wrap requested fields
- fields: names of data you want
- arguments: optional filters or parameters for fields
graphql
query {
user(id: "1") {
id
name
email
}
}Example
This example fetches a user by ID and requests their id, name, and email. It shows how to write a simple query with arguments and nested fields.
graphql
query {
user(id: "1") {
id
name
email
}
}Output
{
"data": {
"user": {
"id": "1",
"name": "Alice",
"email": "alice@example.com"
}
}
}
Common Pitfalls
Common mistakes when writing GraphQL queries include:
- Forgetting to wrap fields inside curly braces
{ }. - Using incorrect field names that do not exist in the schema.
- Not passing required arguments to fields.
- Trying to fetch fields without nesting properly.
Always check the schema for available fields and required arguments.
graphql
Wrong:
query {
user
id
name
}
Right:
query {
user(id: "1") {
id
name
}
}Quick Reference
| Concept | Description | Example |
|---|---|---|
| query | Starts a read operation | query { user { id name } } |
| field | Data you want to fetch | user, id, name |
| arguments | Filter or specify data | user(id: "1") |
| nested fields | Fetch related data inside fields | user { posts { title } } |
Key Takeaways
Start GraphQL queries with the query keyword and wrap requested fields in curly braces.
Specify fields you want exactly as named in the schema, nesting them to get related data.
Pass required arguments to fields to filter or identify data.
Always check the schema to avoid requesting invalid fields or missing arguments.
Use tools like GraphiQL or Apollo Studio to test and explore queries interactively.