Using Postman Collections for Slash GraphQL Administration

Update: On April 16th 2021, Slash GraphQL was officially renamed Dgraph Cloud. All other information below still applies.

Slash GraphQL has a GraphQL admin API, and Postman lets you group API operations into collections; so, what better way to automate common admin operations for Slash GraphQL backends than a Postman collection.

Dgraph’s managed GraphQL backend service, Slash GraphQL, is the fastest way to build serverless GraphQL apps. A nice feature of Slash GraphQL is that one way to administer your backends is with GraphQL queries and mutations.

A previous post showed how to use Postman with GraphQL and Dgraph. The post talked about getting and setting a schema and making GraphQL queries and mutations.

A feature of Postman that we didn’t discuss in the previous blog is collections. Postman collections let you group API operations to keep them organized, and so that variables, like URLs and tokens, can be used throughout the collection. Even better, Postman collections can be shared with others. So, what better way to automate common admin operations for Slash GraphQL backends than a Postman collection.

In this post, we’ll teach you how to use Postman collections with Slash GraphQL’s admin API as an example and we’ll share that collection, so you can use it too.

Collections

Put simply, a Postman collection is a folder where you can keep your API requests and various elements organized. A folder can have sub-folders too. Here, for example, we’re going to see how we can create a collection for administering Slash GraphQL backends. Since this type of work is frequent, a collection is just the thing to keep the admin requests repeatable and separate from the operations we might do with the /graphql API.

The admin collection will contain these four requests:

  • getting a schema
  • setting a new schema
  • exporting data, and
  • dropping data.

In this post, we’ll add these requests from the Slash GraphQL Administering your Backend docs.

Creating a collection

You can access Postman collections in the left sidebar, in the Collections tab.

Collections Tab

To create a collection, click New collection or Create a collection.

Create a New Collection

In the new collection window, you can give your collection a name and a description. Since you’d want to share your collection (more on that later in the post) with others in the process, whatever you put in the description box should reflect what this collection does and its scope.

Add Collection Name and Descrition

Click Create and your collection is added to the collections tab.

New Collection Added

Slash GraphQL

Of course, to administer a Slash GraphQL backend you’ll need one deployed. If you aren’t signed up to build GraphQL apps with Slash GraphQL, you should check out Slash GraphQL and sign up.

After signing up and logging in to Slash GraphQL, you’re greeted with the dashboard.

Slash GraphQL Dashboard

Click on the Launch new backend button in the top-right corner to create a new GraphQL backend. The free tier is fine for this post, but you can admin any Slash GraphQL backend with Postman.

New GraphQL Backend

After you have a GraphQL backend deployed, the dashboard will display information for the deployment, including the URL. Note that down because you’ll need it to access the deployment from Postman.

Dashboard with URL

You’ll need an API key to admin you backend remotely from Postman. Select Settings and then the Security tab, then generate an API key with the Create New button.

Security Settings Tab

Click on Create New, give it a name and designate role (here we’ll choose Admin) and hit Create.

New API Key

Put the generated API key somewhere safe; you can’t access it after navigating away. After generating such a key we’ll include it in our request headers to admin our GraphQL backend. We’re going to use it with Postman in the next section.

Okay, now, back to Postman…

Collection variables

In Postman collections can have variables that apply to all requests in the collection. Our admin collection will use that to set things like the URL of the Slash GraphQL backend and the token.

In Postman select the icon for “View more actions” and from there Edit.

Edit Collection

In the “Edit Collection” window, select the Variables tab. Here, we’ll set values for:

  • URL containing the domain name part of our server address. In my case, it’s https://imperfect-drop.us-west-2.aws.cloud.dgraph.io.
  • TOKEN containing the API key that we created earlier in Slash GraphQL.

Edit Collection Variables

We can use these variables where we need them by placing them inside double curly braces, like this: {{URL}}, within our current workspace and collection. We can hit various endpoints by just specifying that with our variable, like this: {{URL}}/admin, which expands to https://imperfect-drop.us-west-2.aws.cloud.dgraph.io/admin.

Adding requests

Our Slash GraphQL Admin collection will contain the four admin requests mentioned earlier, so let’s add those.

To add a request, click the “View more actions” button on the collection sidebar and then on Add Request.

Add a Request

In the new request window, fill in the request details and click Save to Slash GraphQL Admin at the bottom right to add the request.

Save New Request

Let’s add a request for setting schema by posting an updateSchema GraphQL mutation to the /admin endpoint. We’ll walk through this one because it contains a neat trick with Postman and the others can be patterned off this first one.

  1. Add a request to the collection, name it “Set new schema”, and press Save to Slash GraphQL Admin.
  2. Change the method to POST.
  3. Set the URL field to {{URL}}/admin (when the request is run that will be replaced with the value of the URL variable).
  4. Select the Body tab and set it to GraphQL.

Now, in the body, place the GraphQL mutation to set a schema.

mutation($sch: String!) {
  updateGQLSchema(input: { set: { schema: $sch}})
  {
    gqlSchema {
      schema
      generatedSchema
    }
  }
}

and set the GraphQL variables to set a value for variable $sch

{ "sch": {{newSchema}} }

That’ll look like this in Postman:

Set new schema body

That much says that the request is a GraphQL mutation that relies on a GraphQL variable, but what’s the value of that variable? We’ll fill that in with a Postman pre-request script that adds the schema to a Postman variable — that means you can change it whenever you need to.

Select the Pre-request Script tab and enter this script

var newSchema = `
type User {
    id: ID!
    name: String!
}
`

pm.environment.set("newSchema", JSON.stringify(newSchema));

That’ll look like this in Postman:

pre-request script

Click Save to save the changes to the Slash GraphQL Admin collection. Now you have a ready-to-send request for the collection with a URL and GraphQL mutation.

The three remaining requests are similar, except, no tricks, just GraphQL queries: for example, exporting the database is just this GraphQ mutation sent to {{URL}}/admin/slash

mutation {
  export {
    response { 
        code 
        message 
    }
    signedUrls
  }
}

After adding the remaining requests, the collection overview shows the newly-added requests with all their details:

Collection requests

Adding authorization

We can’t send those requests without using the API key for Slash GraphQL. There are two ways to do that: use the TOKEN variable in the headers of each request, or set the token in the collection’s Authorization tab. We’ll use the second.

Head over to the collection Edit window again and select the Authorization tab. Here we can select our authorization type and enter parameters such as access token, passwords, keys, etc. depending on the type. Since we’re using an API key, you can select API Key as the type and fill the Key and Value fields. Set Key to X-Auth-Token, and Value to {{TOKEN}}.

Collection Authorization Tab

These parameters are added automatically in our request header (notice the Add to set to “Header”).

This way, using collections and variables, we can make our interactions with the admin API a lot easier. By breaking down the whole development and management process into collections and using variables for re-usability and isolation, the process becomes organized, repeatable, and maintainable. Such a scenario is a perfect use-case for Postman with the tools it provides us with.

Using the collection

Let’s see if everything’s working by making a request to get the current schema. Click on the Getting the schema request on the left sidebar of the Collections tab, then click the Send button on the top-right.

Execute Request

You can see the response below in the response Body tab. Sweet! We’re now able to make requests using collection variables. You could for example check our previous post and use the response to set the schema for testing the API of your app.

Sharing a collection

Another nice feature of Postman’s collections is that you can share your work with anyone you want. Sharing a collection gives someone else the ability to start using or collaborating on the collection.

Click on View more actions and there you’d see options for Share Collection and Export.

Postman Export

You can share your collection with another Workspace (normally, say, your colleague/co-worker’s workspace who’s also using Postman), embed it in a public place such as a GitHub README or a website, or just generate a plain sharable public link, as you can see in the new window:

Another way to share, as pointed in the figure above, is to do an Export, which generates a JSON file with all the data. You can send that file to someone else and they can do an Import that would set everything up in their Postman instance and start working right away.

Postman Import

We’ve done that. Here’s the Postman collection we built for this post. You can import that into Postman and start using it to automate your Slash GraphQL admin tasks.

{
  "info": {
    "_postman_id": "720c4b28-0e9b-4625-b1c1-9b2548adcb14",
    "name": "Slash GraphQL Admin",
    "description": "# Administer a Slash GraphQL backend from Postman.\n\nLearn more about Slash GraphQL at https://dgraph.io/cloud.\n\nContains requests for:\n\n* setting a schema\n* getting current schema\n* exporting the database and \n* dropping all data.",
    "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
  },
  "item": [
    {
      "name": "Get the schema",
      "request": {
        "method": "POST",
        "header": [],
        "body": {
          "mode": "graphql",
          "graphql": {
            "query": "{\n  getGQLSchema {\n    schema\n  }\n}",
            "variables": ""
          }
        },
        "url": {
          "raw": "{{URL}}/admin",
          "host": [
            "{{URL}}"
          ],
          "path": [
            "admin"
          ]
        },
        "description": "Get the current schema.\n\nSee docs here https://dgraph.io/docs/slash-graphql/admin/schema/"
      },
      "response": []
    },
    {
      "name": "Set a new schema",
      "event": [
        {
          "listen": "prerequest",
          "script": {
            "id": "ef1c3da4-c6d0-4cb3-910a-2269ddcb3240",
            "exec": [
              "var newSchema = `type User {",
              "    id: ID!",
              "    name: String!",
              "}`",
              "",
              "pm.environment.set(\"newSchema\", JSON.stringify(newSchema));"
            ],
            "type": "text/javascript"
          }
        }
      ],
      "request": {
        "method": "POST",
        "header": [],
        "body": {
          "mode": "graphql",
          "graphql": {
            "query": "mutation($sch: String!) {\n  updateGQLSchema(input: { set: { schema: $sch}})\n  {\n    gqlSchema {\n      schema\n      generatedSchema\n    }\n  }\n}",
            "variables": "{\n    \"sch\": {{newSchema}}\n}"
          }
        },
        "url": {
          "raw": "{{URL}}/admin",
          "host": [
            "{{URL}}"
          ],
          "path": [
            "admin"
          ]
        },
        "description": "Set a new schema for this backend.\n\nSee docs here https://dgraph.io/docs/slash-graphql/admin/schema/"
      },
      "response": []
    },
    {
      "name": "Export data",
      "request": {
        "method": "POST",
        "header": [],
        "body": {
          "mode": "graphql",
          "graphql": {
            "query": "mutation {\n  export {\n    response { code message }\n    signedUrls\n  }\n}",
            "variables": ""
          }
        },
        "url": {
          "raw": "{{URL}}/admin/slash",
          "host": [
            "{{URL}}"
          ],
          "path": [
            "admin",
            "slash"
          ]
        },
        "description": "Export all data from this backend.\n\nThe `signedUrls` field will contain urls for downloading the exported data.\n\nSee docs here https://dgraph.io/docs/slash-graphql/admin/import-export/"
      },
      "response": []
    },
    {
      "name": "Drop data",
      "request": {
        "method": "POST",
        "header": [],
        "body": {
          "mode": "graphql",
          "graphql": {
            "query": "mutation {\n  dropData(alldata: true) {\n    response { code message }\n  }\n}",
            "variables": ""
          }
        },
        "url": {
          "raw": "{{URL}}/admin/slash",
          "host": [
            "{{URL}}"
          ],
          "path": [
            "admin",
            "slash"
          ]
        },
        "description": "Drop all data. \n\nTo drop schema along with all the data, use `allDataAndSchema: true` instead of `allData: true`.\n\nSee docs here https://dgraph.io/docs/slash-graphql/admin/drop-data/"
      },
      "response": []
    }
  ],
  "auth": {
    "type": "apikey",
    "apikey": [
      {
        "key": "in",
        "value": "header",
        "type": "string"
      },
      {
        "key": "key",
        "value": "X-Auth-Token",
        "type": "string"
      },
      {
        "key": "value",
        "value": "{{TOKEN}}",
        "type": "string"
      }
    ]
  },
  "event": [
    {
      "listen": "prerequest",
      "script": {
        "id": "2d248664-1d16-4efa-8ccf-cdce55893f4d",
        "type": "text/javascript",
        "exec": [
          ""
        ]
      }
    },
    {
      "listen": "test",
      "script": {
        "id": "93de6ea0-8844-4f86-882e-cdb4662222b0",
        "type": "text/javascript",
        "exec": [
          ""
        ]
      }
    }
  ],
  "variable": [
    {
      "id": "3b51c06a-0147-480b-a929-e7eeea73d69b",
      "key": "URL",
      "value": "<<your Slash GraphQL URL here>>"
    },
    {
      "id": "36e9f4f7-cf30-41b5-8dc2-16f203a920f3",
      "key": "TOKEN",
      "value": "<<your API token here>>"
    }
  ],
  "protocolProfileBehavior": {}
}

To use the collection, you’ll need to set the variables for URL and TOKEN to the values for your Slash GraphQL backend, and, if you want to update your schema from Postman, set the schema string in the pre-request script for the “Set new schema” request.

Summary

This post has shown you how to use Postman collections and how to admin your Slash GraphQL backend from a postman collection. You can learn some more from these references: