Course contentsShow
← Software Engineering
Lesson 807 of 1,93325. RPC and GraphQL API DesignFree lesson

Queries: Reading Data in GraphQL

Writing queries to request specific fields, understanding selection sets, and how clients control response shape.

Queries: Reading Data in GraphQL

What you'll learn: How to write GraphQL queries that let you request exactly the data you need, no more and no less.

The Core Idea

In GraphQL, a query is how clients read data from the server. Unlike REST where endpoints return fixed data structures, GraphQL queries let you specify precisely which fields you want. Think of it like ordering at a restaurant where you can customize every aspect of your meal, rather than choosing from pre-set combos.

Selection Sets

The heart of a query is its selection set—the curly braces containing the fields you want:

query {
  user {
    id
    name
    email
  }
}

This requests a user with only three fields: id, name, and email. If the user object has twenty other fields in the schema, you won't receive them unless you ask.

Nested Selection Sets

You can nest selection sets to traverse relationships:

query {
  user {
    name
    posts {
      title
      createdAt
    }
  }
}

Here you're fetching a user's name and their posts, but only each post's title and creation date—not comments, likes, or other data.

Clients Control the Response Shape

This is GraphQL's superpower: the query's structure mirrors the response structure. The client gets back exactly what it asked for, shaped exactly how it asked. No over-fetching (getting unwanted data) or under-fetching (needing multiple requests).

The server responds with JSON matching your query structure, making it predictable and easy to work with in your application code.

Key Takeaway: GraphQL queries use selection sets to let clients specify exactly which fields they need, controlling the shape and size of the response and eliminating over-fetching or under-fetching problems.