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

Writing Your First GraphQL Query

Learn the basic syntax of GraphQL queries and how to request specific fields from a GraphQL API.

Writing Your First GraphQL Query

You'll learn: How to construct a basic GraphQL query to request exactly the data you need from a GraphQL API.

The Core Idea

A GraphQL query is essentially a description of the data you want. Unlike REST where you hit specific endpoints and get whatever the server decides to return, with GraphQL you write a query that mirrors the shape of the response you want. Think of it like filling out a form where you check boxes next to only the fields you need—nothing more, nothing less.

Basic Query Syntax

A GraphQL query starts with the query keyword (though it's optional for simple queries), followed by curly braces containing the fields you want to retrieve:

query {
  user {
    name
    email
  }
}

This query asks for a user object and specifies that you only want the name and email fields. The response will match this structure exactly:

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

Requesting Multiple Fields

You can request as many or as few fields as you need. If the user object has name, email, age, and location, but you only ask for name, you'll only get name:

query {
  user {
    name
  }
}

Nested Fields

GraphQL shines when dealing with related data. You can traverse relationships by nesting fields:

query {
  user {
    name
    posts {
      title
      publishedDate
    }
  }
}

Key Takeaway: GraphQL queries let you specify the exact structure and fields you want, eliminating over-fetching and under-fetching—you ask for precisely what you need, and that's exactly what you get back.