Skip to content

GraphQL Queries

In GraphQL, a query is used to request data from the server. Unlike REST, which has multiple endpoints for different resources, GraphQL uses a single endpoint and allows the client to specify exactly what data it needs.


Basic Query Structure

A query starts with the query keyword (optional) and includes:

  • The operation name (optional but recommended)
  • Fields you want to retrieve
  • Arguments (if required)
  • Nested fields

Example

query GetUser {
  user(id: "1") {
    id
    name
    email
  }
}
  • user is a field on the Query type.
  • id, name, and email are subfields of the User type.

Query Without the query Keyword

You can omit the query keyword if there are no variables or operation name:

{
  user(id: "1") {
    name
  }
}

Using Variables

Variables make queries reusable and more secure.

Query:

query GetUser($userId: ID!) {
  user(id: $userId) {
    id
    name
  }
}

Variables:

{
  "userId": "1"
}

Nested Queries

You can request related data in a single query.

{
  user(id: "1") {
    name
    posts {
      title
      comments {
        content
      }
    }
  }
}

GraphQL lets you traverse relationships in one request — reducing the need for multiple round-trips.


Aliases

Aliases allow you to rename fields in the response or request the same field with different arguments.

{
  post1: post(id: "1") {
    title
  }
  post2: post(id: "2") {
    title
  }
}

Fragments

Use fragments to reuse parts of a query.

fragment UserFields on User {
  id
  name
  email
}

query {
  user(id: "1") {
    ...UserFields
  }
}

Inline Fragments

Useful when working with unions or interfaces.

{
  search(term: "GraphQL") {
    ... on User {
      name
    }
    ... on Post {
      title
    }
  }
}

Directives

You can conditionally include or skip fields with @include and @skip.

query GetUser($withEmail: Boolean!) {
  user(id: "1") {
    name
    email @include(if: $withEmail)
  }
}

Response Shape Matches Query Shape

GraphQL responses mirror the structure of the query.

Query

{
  user(id: "1") {
    name
    email
  }
}

Response

{
  "data": {
    "user": {
      "name": "Alice",
      "email": "alice@example.com"
    }
  }
}

Best Practices

  • ✅ Only request the data you need
  • ✅ Use variables instead of hardcoding values
  • ✅ Use fragments for reusable fields
  • ✅ Use aliases to fetch multiple variations of the same field
  • ✅ Avoid deeply nested queries unless necessary

Tools


Summary

  • Queries are the primary way to read data in GraphQL.
  • You control exactly what fields and relationships are returned.
  • GraphQL queries are powerful, efficient, and flexible, replacing the need for multiple REST endpoints.