Chapter 6: Sanity's GraphQL Playground

This chapter introduces GraphQL, a powerful query language. Sanity's GraphQL API enables external programs to interact with its structured content while following the standard that it provides. This allows developers to leverage the rich GraphQL ecosystem of tools and practices that are available in the development community. Both GraphQL and GROQ, which is Sanity's proprietary query language, are open source and can be used to interact with Sanity. However, while GROQ is specific to Sanity, GraphQL is universally used by many applications.

In this chapter, we will explain what GraphQL is, examine some of the basic queries and their format, introduce Sanity's GraphQL Playground, and learn how to use it to create and test GraphQL queries. In this chapter, we will cover the following topics:

  • An introduction to GraphQL
  • GROQ versus GraphQL
  • Sanity.io's GraphQL playground basics

Technical requirements

A web browser and a Terminal program are required.

An introduction to GraphQL

First, let's start by learning about GraphQL. From the GraphQL website, we learn that GraphQL allows its user to describe the data. This means defining how a data structure should be formed. Consider the following example:

type Event {

  name: String

  date: Date

}

Here, we define the structure of an event. Using GraphQL, we could query the data structure as follows:

{

  event(name: "Saturday Night Party") {

    date  

  }

}

Notice that the basic structure looks almost the same. We are asking for the data to be in the same format as it is defined. The returned data would be in the following format:

{

  "event" {

    date: "2020-10-01"

  }

}

Note:

For more information on GraphQL's syntax and specification, please visit http://spec.graphql.org/draft/.

GraphQL's strength is that it gives its users the ability to request specific information and to obtain predictable results that mirror those requests.

In the following sections, we will learn about why GraphQL is a compact and efficient standard making it useful to obtain data from many data sources such as Sanity.

We will continue our journey into the world of GraphQL by deploying the GraphQL schema and using Sanity's command-line deployment tool.

Deploying the GraphQL API

Since Sanity uses GROQ internally, the optional GraphQL API needs to be deployed if Sanity's dataset is used by other applications. To perform this, we need to return to the command line in the project's studio directory.

The following command needs to be typed into the Terminal:

sanity graphql deploy

We need to install the Sanity command-line program. Please type the following into the command line if it has not been installed already:

npm install -g @sanity/cli

You will be asked the following question:

Do you want to enable a GraphQL playground? (Y/N)

At this prompt, simply pressing the Enter key, or typing in Y, will enable the playground. The last line of the output that is produced should display the playground's browser:

GraphQL API deployed to:

https://abcd1234.api.sanity.io/v1/graphql/production/default

This URL can be opened in the web browser. Let's examine the format.

Notice that the URL is composed of the following: the project ID (which is shown here as abcd1234), followed by api.sanity.io, v1 (version one), graphql, the dataset name (in this example, production), and, finally, the schema name (in this case, default).

In the next section, we will explore the basic syntax of GraphQL.

Basic GraphQL syntax

While Sanity's GROQ uses a more compact syntax, its aim is to effectively get what you need from a collection of data. GraphQL's aim is to allow the requesting service to specify the format of the data in an expressive and typed way to be returned, and then return it in that same format. We will now look at the basic syntax of a GraphQL query and how useful it might be to obtain data easily.

There are two basic types of queries:

  • The all prefix followed by the schema, name, as shown in the following, is used to return multiple records.
  • The single-record query, which will return only one record.

Let's start by learning about the all query format.

GraphQL's all query

Consider the following example query:

{

  allEvent {

    name

  }

}

The preceding query will return the name for all of the events in our dataset. The singular form of event is used here instead of the plural form. The result will be in the same format as the query. Notice that the results are wrapped in a data object. Additionally, the allEvent query is repeated in the result, and the result is in the same format as the query:

{

"data": {

    "allEvent": [

      {

        "name": "IT Conference"

      },

      ...

    ]

  }

}

Next, let's learn about the single-record GraphQL query.

GraphQL's single-record query

The second type of GraphQL query will return only one record. The following snippet is an example of this second type of query:

{

  Event(id: "6ddd2730-9aca-46dd-a7fd-850ab306f7fb"){

    name

  }

}

Notice that this type of single-record query needs an argument to identify the record. In this case, the id parameter of the event is used.

This will return a single event. The result is in the same format as the query. Notice that the Event query is repeated in the results:

{

  "data": {

    "Event": {

      "name": "IT Conference"

    }

  }

}

Now that we have learned about the basic syntax of GraphQL, let's delve more deeply into it. In the next section, we'll view the difference between GROQ and GraphQL.

GROQ versus GraphQL

In Chapter 5, Sanity's GROQ Language, in the Advanced GROQ section, we wrote a GROQ query that returned all of the events for a particular venue. Now we will compare GROQ with GraphQL.

Recalling the GROQ syntax, the desired venue was named Will's Pub:

*[_type == "event" && venue->name == "Will's Pub"]{

  name,

  venue->{name}

}

Next, let's write the corresponding GROQ query in GraphQL:

{

  allEvent(where:

  { venue:

    { name:

      { eq:

   "Will's Pub"

      }

    }

  }

)

  {

    name

    venue {

      name

    }

  }

}

GROQ's type == "event" equates to allEvent, which is a function. Note that the GraphQL uses SQL's familiar where keyword, which is a parameter. This is then followed by an object as an argument, which is venue. Here, the venue's name parameter is nested within venue. Then, eq is the two-letter abbreviation for equals.

This concludes the function-argument-parentheses set. Then, between curly braces, we list the fields that we are interested in returning. Notice that GraphQL does not use commas between each value, while GROQ does. We return the event name (name) and also the venue name, which, again, is nested.

The result is as follows:

{

  "data": {

    "allEvent": [

      {

        "name": "The Appleseed Cast",

        "venue": {

          "name": "Will's Pub"

        }

      },

      {

        "name": "Friday Drinks",

        "venue": {

          "name": "Will's Pub"

        }

      }

    ]

  }

}

As you can see, two events are returned. If only the event, named The Appleseed Cast, should be returned, an additional argument to the where keyword can be added. There will be a comma separator. Note that this is the event name, not the venue name, as both fields had the same name:

{

  allEvent(where: { venue: { name: { eq: "Will's Pub" } },

               name: { eq: "The Appleseed Cast" }

} ) {

    name

    venue {

      name

    }

  }

}

The result will now still be a list (that is, an array) because allEvent is used; however, the list will only have one value:

{

  "data": {

    "allEvent": [

      {

        "name": "The Appleseed Cast",

        "venue": {

          "name": "Will's Pub"

        }

      }

    ]

  }

}

This will be important to remember later, as the results will be handled as if there is more than one result.

In the next section, we will use the Sanity.io playground to run GraphQL queries against our Studio application.

GraphQL playground basics

In Chapter 5, SSanity's GROQ Language, in the Installing Vision section, Sanity's Vision tool was used to test the GROQ queries. Likewise, Sanity uses the GraphQL playground so that we can test GraphQL and interact with its datasets.

The GraphQL playground allows users to create and run GraphQL queries that can later be used to obtain information from a GraphQL API. In the following section, we will learn about its basic functionality.

The following is a screenshot of the GraphQL playground:

Figure 6.1 – The GraphQL playground

Figure 6.1 – The GraphQL playground

The GraphQL playground's interface is easy to use. Similar to the Vision GROQ tool, the queries are typed into the left-side window and are executed by clicking on the play icon in the middle of the interface.

As expected, the GraphQL results are displayed in the right window. Query variables may be entered into a bottom window.

On the right, there is a green-colored tab, labeled SCHEMA. Clicking on this will reveal the various GraphQL starting points, such as allEvent. Navigating through this schema is a convenient way to determine whether the GraphQL was deployed correctly after typing in the Sanity graphql deploy command. This command is required after any changes to the schema are made in Sanity.

If a schema or schema field is not viewable here, then it will not be accessible to any external service that uses this API, so it's a convenient way to check that the schema reflects the actual state of the dataset. In the following code block, a basic query format is displayed, together with the type of value expected for each parameter:

allEvent(

  where: EventFilter

  sort: [EventSorting!]

  limit: Int

  offset: Int

): [Event!]!

This is how it might look on the screen upon clicking on the allEvent link:

Figure 6.2 – allEvent details

Figure 6.2 – allEvent details

Query parameters

One of the most important features of the GraphQL playground is its ability to allow the user to add parameters. This is because, in most real-world applications, query parameters will be often used to obtain the correct results. Expand on the QUERY VARIABLES window by dragging it with the mouse. Then, you can enter in key and value pairs, as follows:

{"name": "Will's Pub"}

Figure 6.3 – The Sanity playground's query parameters

Figure 6.3 – The Sanity playground's query parameters

Then, the parameter may be used as follows:

query myQuery($name: String)

{

  

  allEvent(where: { venue: { name: { eq: $name } } }) {

    name

    venue{

      name

    }

    eventUrl

  }

}

The name is passed into the query function, arbitrarily myQuery, in this scenario. Note that the parameter uses a dollar sign prefix. Then, after the colon, the string is used to specify which type of value will be passed into the function. Then, $name is used in place of Will's Pub for the expression "the venue name equals…". Modeling parameter passing is useful for testing.

Summary

In this chapter, we learned how GraphQL is formed, how GraphQL differs from GROQ, and how to filter results using where. Finally, we learned how to use Sanity's GraphQL playground to construct and verify the schemas, and we looked at examples. GraphQL will be the means by which all programs wishing to connect to Sanity might easily do so in a standard and compact way. In the following chapters, GraphQL will be important since the static-site generator will use it exclusively.

In the next chapter, we will introduce Gatsby, another part of the Jamstack. We will use some of the GraphQL examples shown here in order to connect Sanity's datasets to Gatsby.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.134.104.173