How to Define Fields for Query Operation

Learn about the query operation in GraphQL.

Let’s start with the basics of GraphQL.

A language for defining schemas (SDL)

GraphQL has a certain writing system for defining an API’s schema. Schema Definition Language is the syntax for writing schemas (SDL).

Here’s a sample of how to define a basic type called Pizza using SDL:

Press + to interact
type Pizza {
id: Int!
pizza: String!
}

This type contains two fields: id and name, which are Int and String, respectively. The ! after the type indicates that this field is required.

Imagine there’s one more simple type called Topping.

Press + to interact
type Topping {
id: Int!
topping: String!
}

With GraphQL, it’s possible to express relationships between types. In the example of your pizza application, a Pizza could be associated with a Topping:

Press + to interact
type Pizza {
id: Int!
pizza: String!
toppings: [Topping!]!
}

Note: toppings: [Topping!]! Every pizza can’t have empty toppings and every topping must be defined. You will learn more about this in the next lesson.

Note that you just created a one-to-many relationship between Pizza and Topping since the toppings field on pizza is actually an array of toppings. You will learn more about the schema in another lesson.

Fetching data with queries

When interacting with REST APIs, data is fetched from multiple endpoints. Each endpoint has a defined structure of the information that it returns.

In GraphQL, instead of fetching multiple endpoints that return fixed data structures, GraphQL APIs typically only exposes a single endpoint.

This works because the data is completely flexible, so the client decides what is needed. This means that the client needs to send more information to the server to express its data needs - this information is called a query.

Let’s take a look at an example query that a client could send to a server:

Press + to interact
{
pizzas {
pizza
}
}

The query above would return a list of all pizzas currently stored in the database. Here’s an example response:

{
  "data": {
    "pizzas": [
      {
        "pizza": "Neapolitan Pizza"
      },
      {
        "pizza": "Chicago Pizza"
      },
      {
        "pizza": "New York-Style Pizza"
      },
      {
        "pizza": "Sicilian Pizza"
      },
      {
        "pizza": "Greek Pizza"
      },
      {
        "pizza": "California Pizza"
      },
      {
        "pizza": "Detroit Pizza"
      },
      {
        "pizza": "St. Louis Pizza"
      }
    ]
  }
}

Notice that each pizza only has the name in the response. If the client needs more data, all it has to do is slightly adjust the query and include the new field in the query’s payload:

Press + to interact
{
pizzas {
id
pizza
}
}

Note: GraphQL query operation requires fields to be defined.