GraphQL quick tip: How to pass variables in GraphiQL

In the previous articles basic GraphQL setup in express and JSON as an argument for GraphQL mutations, we used GraphiQL for executing queries and mutations. We mentioned the following different forms of passing an argument into a mutation

  • Using inline arguments
  • Using variables

Now let’s discuss how we can perform query executions using inline arguments and variables in GraphiQL as we did not mention that in previous articles. First just clone this repository and switch to the corresponding branch to test our example mutation

git clone https://github.com/a7v8x/express-graphql-demo.git -b feature/2-json-as-an-argument-for-graphql-mutations-and-queries

The process of designing mutations is described in the article on GraphQL mutations. We will use the same example of a mutation, nevertheless, in this quick blog post we will focus only on our options for executing mutations and queries in GraphiQL.

Inline arguments in GraphiQL

First we can use inline arguments. The mutation execution string is then written as follows and there are no other requirements for executing mutation written in this format

mutation for creating user with inline arguments

Variables in GraphiQL

With the variables is a little bit more complex we have to split query string into two separate parts. Our selection set includes id, username, email, phone, firstName and lastName like in the query string with inline arguments

mutation for creating user with variables

If we would like to use the variables in GraphiQL just click on the QUERY VARIABLES panel at the bottom of your screen and pass the following code

example of JSON with variables

Variables should be written using the JSON format. Therefore if you add for example a comma at the end of the last attribute, the GraphiQL invalidates the object with the variables.

The overview of your setup can be viewed like this

I use passing variables using GraphiQL all the time. We can easily copy and paste the code to our *.graphql files and instantly know that we are building them correctly. The only problem to think about is that we have to debug our input variable to be in a format which can be validated by our GraphQL schema. The project setup with queries in *.graphql files will be the topic of one of our future articles on GraphQL mastery.

Checkout the upcoming free GraphQL language course with in browser exercices
From upcoming GraphQL Language course
Did you like this post? Then clap for this article as it is easier for others to find it. The repository with the examples and project setup can be cloned from this GitHub branch. You can get early access to upcoming free GraphQL course by subscribing at graphqlmastery.com.