Executing queries in GraphQL

Tutorial 3 of 5

1. Introduction

1.1 Goals

This tutorial aims to take you through the process of executing queries in GraphQL. We'll cover how to fetch data using queries and how to shape the response data.

1.2 Learning Outcomes

By the end of this tutorial, you will be familiar with:
- Writing and executing GraphQL queries
- Shaping response data
- Handling errors in GraphQL queries

1.3 Prerequisites

To follow this tutorial, you should have a basic understanding of:
- JavaScript
- REST APIs
- Basic knowledge of GraphQL (optional but beneficial)

2. Step-by-Step Guide

2.1 GraphQL Queries

In GraphQL, a query is used to read or fetch values. They are similar to the 'GET' requests in REST APIs.

2.2 Writing a Query

A basic GraphQL query looks like this:

{
  products {
    name
    price
  }
}

In the above example, we are querying a list of products and requesting two fields: name and price.

3. Code Examples

3.1 First Query

Here's a simple query to fetch user data:

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

In this example, we are fetching a user by his ID and requesting two fields: name and email.

3.2 Query with a Complex Object

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

In this example, we are fetching a user and his friends' names. The friends field returns an array of complex objects, and we are requesting the name field from each of those objects.

4. Summary

In this tutorial, we learned to write and execute GraphQL queries. We learned how to fetch data and shape the response data. We also discussed handling errors in GraphQL queries.

5. Practice Exercises

5.1 Exercise 1

Write a GraphQL query to fetch a list of books with the title, author, and publishedDate.

5.2 Exercise 2

Write a GraphQL query to fetch a user's posts and the comments on each post. Request the title field from the posts and the text field from the comments.

5.3 Exercise 3

Write a GraphQL query to fetch a list of courses. For each course, request the name and description fields. Also, fetch the name and email of the instructor of each course.

For further practice, try to write more complex queries that fetch data from multiple nested objects. Also, check out the official GraphQL documentation for more information.