Course contentsShow
← Web Development
Lesson 1525 of 2,98228. GraphQL FundamentalsFree lesson

Writing Your First Query

Constructing basic GraphQL queries to fetch data with specific field selections.

Writing Your First Query

You'll learn how to construct a basic GraphQL query to request exactly the fields you need from the server.

The Core Idea

A GraphQL query is like ordering from a customizable menu—you specify exactly which dishes (fields) you want, and the kitchen (server) delivers only those items. Unlike REST where you get a fixed response, GraphQL lets you pick and choose your data shape.

Query Syntax Basics

In GraphQL, queries follow this structure:

query {
  fieldName {
    subField1
    subField2
  }
}

The outer query keyword (often optional for simple queries) tells GraphQL you're reading data. Inside, you specify which root Query fields you want to access.

A Real Example

Suppose your GraphQL schema has a user field that returns an object with id, name, email, and bio fields. Here's how you'd request just the name and email:

{
  user {
    name
    email
  }
}

Notice you're not getting id or bio—only what you asked for. The response mirrors your query structure:

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

Multiple Fields at Once

You can request multiple root fields in one query:

{
  user {
    name
  }
  posts {
    title
  }
}

This fetches both user data and posts data in a single round trip—no multiple REST endpoints needed.

Key Takeaway: GraphQL queries let you declare exactly which fields you need using a syntax that mirrors the JSON response structure, giving you precise control over data fetching.