GraphQL Fundamentals: Queries

GraphQL Fundamentals: Queries

GraphQL has two basic types of operation:

In this article, I am going to show you how to deal with GraphQL queries.

Prerequisites

I will show you some examples using PWA Studio, so if you want to experiment by yourself, you will have to install PWA Studio on your computer. Y ou can find instructions on how to do it in my recent articles or in the official PWA Studio docs

GraphQL Playground

Hopefully, you have installed PWA Studio, so now you are able to use the GraphQL playground and play around with queries a little bit!

GraphQL playground

The first query

Let’s try to get to all countries!

Loading...

How simple is that?

getCountries is the name of the query. The ‘countries’ objects can be used to request data about all available countries – ‘countries’ is an object in GraphQL terms. Objects hold data about an entity. Each object has fields. In our case, we used the ‘full_name_locale field’, but there are more fields for the countries object. Take a look at the docs:

figure

The results of this query may look like this:

figure

Congratulations! You made your first query! You are well on your way to becoming a GraphQL master, really!

figure

Query with variables

Now we are going to do something more difficult, like a query with variables.

Let’s query for a specific CMS Page, for instance, for the Homepage:

Loading...

As you can see here, we have information about variables: $identifier: String!

This means that the query expects a “$identifier” parameter that is of type String. Mark! means that this parameter is required. If you run this query without a variable, you will see an error like this:

figure

If you provided a variable, and a page with the given ID existed in the Database, you would see results like this:

figure

You can also specify a default variable in GraphQL. It works only for non-required arguments. Take a look:

figure

Nested objects

You can request nested objects in one query, and you can specify variables for all objects in this way:

Loading...

The results may look like this:

figure

Directives

Directives let you perform a conditional query for objects. There are two types of directives: include, and skip. You can pass a bool variable to query, and then use this variable in the directive. Take a look at how it works:

Loading...

The results may look like this:

figure

GraphQL queries: Summary

Hope you enjoyed our quick tour through GraphQL queries. It would be great if you practiced a little on your own. To help you, I have prepared a few simple tasks for you:

Did you like it? Share!

Each share supports and motivates me to create new content. Thank you!

About the author

Marcin Kwiatkowski

Certified Magento Full Stack Developer, based in Poland. He has 7 years of professional Software engineering experience. Privately, husband, father, and DIY enthusiast.

Read more

You may also like