Queries in GraphQL
Queries are how you read data from a GraphQL API. They're the most common operation and the starting point for most GraphQL interactions.
When you write a query, you specify exactly what data you want and the server responds with just that data.
Basic Queries
A basic query requests data from the root Query type. You specify which fields you want, and the server returns those fields.
// Query for a single user
query {
user(id: "1") {
name
email
}
}
// Response
{
"data": {
"user": {
"name": "Alice",
"email": "alice@example.com"
}
}
}
Notice how the response shape matches the query shape. You asked for name and email, so that's exactly what you got.
Querying Lists
When a field returns a list, you can query multiple items at once:
// Query all users
query {
users {
id
name
email
}
}
// Response
{
"data": {
"users": [
{ "id": "1", "name": "Alice", "email": "alice@example.com" },
{ "id": "2", "name": "Bob", "email": "bob@example.com" }
]
}
}
The server returns an array because the users field is defined as [User!]! in the schema.
Nested Queries
One of GraphQL's superpowers is querying related data in a single request:
// Query users with their posts and comments
query {
users {
name
posts {
title
comments {
text
author {
name
}
}
}
}
}
This single query fetches users, their posts, and the comments on each post, including who wrote each comment. In REST, this would require multiple API calls.
// Response
{
"data": {
"users": [
{
"name": "Alice",
"posts": [
{
"title": "My First Post",
"comments": [
{
"text": "Great post!",
"author": { "name": "Bob" }
}
]
}
]
}
]
}
}
Query Arguments
Queries can accept arguments to filter or specify data. These arguments are defined in the schema.
// Schema with arguments
type Query {
user(id: ID!): User
users(role: Role, limit: Int): [User!]!
searchUsers(query: String!): [User!]!
}
// Using arguments
query {
users(role: ADMIN, limit: 10) {
name
email
}
}
query {
searchUsers(query: "alice") {
name
}
}
Arguments let you filter, sort, and paginate data right from the query.
Named Queries
You can give your queries names for better debugging and readability:
// Named query
query GetUserWithPosts {
user(id: "1") {
name
email
posts {
title
}
}
}
Named queries are helpful when you have many queries in your application. The name shows up in logs and debugging tools, making it easier to track what's happening.