In this blog

This article assumes that the reader understands the basics of GraphQL. You may want to go through a brief Introduction to get up to speed.

We will be using the SpaceX GraphQL API (https://api.spacex.land/graphql/) for the demo.

Obtain GraphQL Schema from a server

Though obtaining the schema is not always required, it certainly helps to be able to review it for the supported queries, mutations and their definitions. 

Usually, getting the schema is straightforward and involves a simple download of the .json/.graphql schema files. At times when the schema file is not directly accessible, it may be downloaded from the server using the apollo npm package.

Pre-Requisite Installations

npm install -g apollo

npm install -g graphql-introspection-json-to-sdl

Download the Schema

For the SpaceX API, use: apollo schema:download --endpoint=https://api.spacex.land/graphql/

Replace https://api.spacex.land/graphql/ with your GraphQL API endpoint URL.

This will download the schema in JSON format. To convert it to graphql format, use the following command:

graphql-introspection-json-to-sdl schema.json > schema.graphql

** Tip: While downloading, If you encounter the following error, install an additional GraphQL npm package using npm install -g graphql Cannot find module 'graphql/validation/rules/KnownArgumentNamesRule' from 'node_modules/@apollo/federation/dist/composition/validate/preNormalization/tagDirective.js' 

Import a GraphQL Schema in Postman - Enable Autocompletion

The above schema (.graphql) can be loaded in the Postman API section - Add a New API with GraphQL type and click Generate Collection. See the attached video for detailed steps.

By Importing the GraphQL Schema, the GraphQL query editor will automatically leverage this schema to provide features such as autocomplete.

** Tip: Use GraphQL SDL in the API definition instead of JSON if you are facing autocomplete errors.

Write a GraphQL Query in Postman

There are a few options to send a GraphQL request in Postman:

GraphQL mode with application/json

Select the GraphQL body type option. This enables us to write a native GraphQL query. Specify the request URL - in our case, it is https://api.spacex.land/graphql/

Change the method to POST - this is necessary since all GraphQL operations work on top of the HTTP POST method. The Content-Type is automatically set to application/json.

The following query fetches the name, founder, ceo and employees of the company SpaceX.

query {
 company {
   name
   founder
   ceo
   employees
  }
}

Response: 

{
   "data": {
        "company": {
            "name": "SpaceX",
            "founder": "Elon Musk",
            "ceo": "Elon Musk",
            "employees": 7000
        }
    }
}
raw mode with application/json

Choose the body type  raw and format as JSON. Create a new JSONObject with property name = query, and property value = the actual query. Remove any white space from the query.

In the following example, we are fetching all the users and returning their id and name

{
    "query":"query{users{id,name}}"
}

The keywords query, mutation are optional. And so is the operation name which follows the query/mutation keyword.

** Tip: It is recommended to use the operation name for easier logging and debugging.

raw mode with application/graphql

A few GraphQL API servers use the express-graphql body parser middleware. In this case, the Content-Type: application/graphql header is supported with raw mode. 

See the following videos for details on writing a query and a mutation.

Using Variables

Let us look at a query that accepts an argument as a parameter. In this example, we are going to get a launchpad. This query requires the id of the launchpad.

    query {
      launchpad(id:"vafb_slc_3w"){
        id,
        location{
          latitude,
          longitude,
          name
        }
      }
    }
Query using variables

The query above can be written to accept dynamic values using variables in GraphQL. 

This involves three steps:

Query accepting dynamic values using Variables

Operation type (query) is required when the variables are being used.

Variables in Postman

Using GraphQL Pre-Request Scripts 

Mutation in a Pre-Request Script

Let's look at a mutation in a Pre-Request Script. The scenario that we are trying to achieve:

  1. Create a new user, and save its id (Pre-Request Script)
  2. Query the user using its id from step 1 (Main API Request)
Step 1  - The Pre-Request Script

The mutation needs to be specified as the body of the request. Even though it's a mutation, the keyword query is used.

const postRequest = {
 url: pm.collectionVariables.get("url"),
 method: 'POST',
  header: {
   'Content-Type': 'application/json',
  },
 body: JSON.stringify({query: 'mutation{insert_users(objects: {name: "Lisa"}){returning{id}}}'})
};

pm.sendRequest(postRequest, (error, response) => {
   pm.variables.set("userId", response.json().data.insert_users.returning[0].id);
});

The user will get created and its id will be returned. In the response, this value is being stored in the variable userId

** Tip: Use a query/mutation from your previous work. Condense it into one line by removing extra space. Specify only those output variables that are needed for the main API request.

Step 2 - The Main Request

Use the userId obtained from Step 1 to specify the value of the id parameter

{
 users(where: {id: {_eq: "{{userId}}"}}) {
   id
   name
   timestamp
  }
}

** Tip: The variables in postman can be referenced by enclosing the variable name in a set of double curly braces. 

Query in a Pre-Request Script

A query can just as easily be specified in the Pre-Request Script. The scenario that we want to achieve:

  1. Get the Id values of all the users ordered by timestamp ascending (Pre-Request Script)
  2. Update the last user from the list in step 1 (Main API Request)
Step 1 - The Pre-Request Script

The query needs to be specified as the body of the pre-request API call. 

const postRequest = {
 url: pm.collectionVariables.get("url"),
 method: 'POST',
  header: {
   'Content-Type': 'application/json',
  },
 body: JSON.stringify({query: '{ users(order_by: {timestamp: asc}) {id}}'})
};
pm.sendRequest(postRequest, (error, response) => {
   var listusers = [];
   for (i = 0; i< response.json().data.users.length; i++){
        listusers.push(response.json().data.users[i].id)
    }
   pm.variables.set("lastUserId", listusers[listusers.length-1]);
});

All the ids are stored in an array. The last id is being stored as a variable lastUserId that can be used in our Main API Request.

Step 2 - The Main Request

Update the last user that has been created. Use the lastUserId variable from Step 1.

mutation updateUserNames{
   update_users(where:{id: {_eq: "{{lastUserId}}"}}, _set:{name:"Dr Watson"}){
        returning{
            id
            name
        }
    }
}

** Tip: Use Postman console for debugging Pre-Request scripts.

Conclusion

We can easily test GraphQL using Postman. We can import the schema and use GraphQL introspection feature to enable autocomplete. We can write queries and mutations, and use dynamically accepted values using variables. And if there are any pre-conditions to your test, those can be scripted in the Pre-Request section of Postman.