Learn from experts and connect with global tech leaders at POST/CON 24. Register by March 26 to save 30%.

Learn more →
X

How to write automated tests for APIs using Postman – Part 1

Avatar

One of Postman’s most powerful features is its ability to run automated tests on your requests. To get you started quickly we are publishing a two-part tutorial series, where we’ll go from a simple test to writing complicated tests and running them inside the Collection Runner. This is the first tutorial in the series.

Test editor

When you open Postman, you should see the ‘Tests’ section in the request editor area.

Screen Shot 2016-06-25 at 05.21.43

To the right of the test editor, there is a list of snippets. You can click on any snippet title and the corresponding code snippet will be appended to the test editor. This makes writing simple tests extremely fast.

This list will be updated as Postman’s test capabilities improve. You’ll also be able to add custom snippets in a future version.

Writing a simple test

Let’s write a simple test to give you a feel of how everything fits together. We’re going to use a new demo API that we have set up – echo.getpostman.com, and which you can use while following this tutorial.

Postman tests are written in Javascript. Postman expects the special tests object to be populated with a description and the result of the test. Postman renders the results in the “Tests” tab as well as in the Collection runner, depending on the boolean values present in this dictionary.

For our first test, we’ll send a GET request to http://echo.getpostman.com/get to find out the status of the API. We’ll check if the status code is 200, and if the Content-Type header is “application/json”. Follow the steps below:

  1. Set the URL to http://echo.getpostman.com/get
  2. Scroll down in the snippets editor and click on the “Status code: Code is 200” snippet.
    Screen Shot 2016-06-25 at 05.24.17

  3. We do not need to make any changes in this case. Let’s send this request right away.

  4. Switch to the “Tests” tab. We see that this test has passed as the correct status code is returned.

Screen Shot 2016-06-25 at 05.25.35

  1. Just to see how things look when the API does not behave as expected, let’s change the status code in the test to 201 and send the request again.

Screen Shot 2016-06-25 at 05.25.49

  1. In the tests tab, Postman tells us that the test has failed (expectedly).
  2. Let’s add another test for the Content-Type header. We want to make sure that the Content-Type header exists and it is equal to “application/json”
  3. responseHeaders is a dictionary available inside the Postman test sandbox which contains all the headers returned in the response. Select the “Response headers: Content-Type header check” snippet.
  4. We’ll change this test a bit. We’ll assign the result of the responseHeaders.has() function to a variable contentTypeHeaderExists.
  5. Remember that as Postman tests are just Javascript code, we can add conditionals like if to our code. We’ll first check if contentTypeHeaderExists is true. If yes, we’ll check if it’s equal to application/json.

Write the following snippet in the test editor:


var contentTypeHeaderExists = responseHeaders.hasOwnProperty("Content-Type");

tests["Has Content-Type"] = contentTypeHeaderExists;

if (contentTypeHeaderExists) {
    tests["Content-Type is application/json"] = 
      responseHeaders["Content-Type"].has("application/json");
}

This is how it should look like inside Postman:

Screen Shot 2016-06-25 at 05.27.19

  1. Send the request.
    Screen Shot 2016-06-25 at 05.27.13

Everything seems to be fine with this API as all our test cases have passed. In case, something breaks down, these tests will fail.

And that’s all it takes. Usually API testing requires a huge amount of boilerplate code. By giving you an integrated environment, Postman aims to make this process painless.

Even if you are new to programming, it’ll just take you a few minutes to write tests with Postman. In the next article, we’ll create a more elaborate test suite. Keep following this blog for updates. You can follow Postman on Twitter (@getpostman).

The “How to write automated test with Postman” series

  1. Part 1 (this article)
  2. Part 2
  3. Part 3

Update: See how to write tests using the newer PM API (known as the pm.*API).

Comment

Your email address will not be published. Required fields are marked *


This site uses Akismet to reduce spam. Learn how your comment data is processed.

26 thoughts on “How to write automated tests for APIs using Postman – Part 1

  • Avatar

    Hi, does it exist a way to compare a json result to a full static json reply ?

    • Avatar

      You can use the JSON validator built into the runner. You can also just compare a response directly as the responseBody variable is just a string.

  • Avatar

    Is there a way to integrate Postman into a continuous integration environment, such as Jenkins? Is there a way to run Postman from the command line?

  • Avatar

    i don’t know how to upgrade my postman in order to make use of this feature.
    where should I pay for that?
    i don’t see any upgrade button

  • Avatar

    I have a question:

    I want to set envVar or globalVar within my tests based off a href response I get:

    {
    href: “http://api.alpha.com/profiles//8a5c7d62332067b48473350171ba4206”
    }

    So in my test box I’ve entered the flowing code to extract and set the profile_id variable yet it goes unset.

    var data = JSON.parse(responseBody);

    postman.setEnvironmentVariable(“profile_Id”, data.substring(37));

    Does this functionality exist within the Jetpacks plugin for postman?

  • Avatar

    Hi. How would I write a test for this case:

    I have an xml response that has something like classes=”3″ and I am writing the test this way:
    tests[“Body matches string classes “] = responseBody.has(classes=”2″);

    the test is passing even when I am testing for it to be 2
    it seems like it is passing whenever 2 is in the XML and ignoring the string classes=”2”

    how would I fix that, please?

  • Avatar

    http://localhost:8080/MyChild3/api/login/status i just want to check the status but i am getting error

  • Avatar

    How do I copy/move tests/folders form one collection to other collection? I have been doing manually moving the tests between collections , but it gets tedious when I have number of tests.

  • Avatar

    Thanks was able to complete following the tutorial. That 14 days free trial is very less.

  • Avatar

    can you please guide me that Postman can operate on different Browers? Kindly Name them for me.. You can mail me using Aynee10@gmail.com

  • Avatar

    demo.getpostman.com link is not working anymore

  • Avatar

    Where are the result details for a test that fails? Is there something like Expected but Actual so you can see why it failed.

  • Avatar

    Uptime Cloud Monitor supports monitoring REST APIs on a completely SAAS based model.
    The setup is quick and easy. You can configure the REST API URL, the REST method (GET/ POST/ PUT/ DELETE), request parameters (if any), credentials required (if any), the monitoring frequency, the geographic location of the monitoring stations (from a choice of 15 stations across the globe). You can match the REST API response body against a specific string to ensure that the response is as expected.

    You can also configure alerts (notified via SMS, Email, PagerDuty etc) to be triggered based on API downtime, performance degradation or API response verification failure.

    More details on REST API Monitoring: http://community.idera.com/blog/b/community_blog/posts/new-rest-api-monitoring-using-uptime-cloud-mo

    More details on Uptime Cloud Monitor Pricing options: https://www.idera.com/infrastructure-monitoring-as-a-service/pricing

    You can sign up for a 14 day free trial of Uptime Cloud Monitor here: https://www.idera.com/infrastructure-monitoring-as-a-service/freetrialsubscriptionform

    Disclaimer: I work at Uptime Cloud Monitor.

  • Avatar

    HI ALL,

    To write automated test scripts in postman.. can we use Java language?
    Or it supports only java script?..

    Please do answer…

    • Avatar

      Only supports Javascript at the moment.

  • Avatar

    Excellent introduction, I had been searching for a basic intro to using Postman for Test

  • Avatar

    Hi,

    It seems like you’ve forgotten a letter in a word “an” 🙂

    “Postman expects the special tests object to be populated with a description an the result of the test.”

  • Avatar

    I had to stare at the first image for about 10 seconds before I found the “Tests section” that you talk about. I’m sure it’s very clear when you know what you’re looking for, but there’s a lot going on in that image. Eye’s are automatically drawn to bottom right side of the image, because it contains orange text on a white background. Adding a big red circle, or some sort of attention grabber, around the “Tests section” would surely help. Thanks.

  • Avatar

    How to write script for Bearer token as it expires in minutes

  • Avatar

    How would you set up and destroy data and include this in automation? Thanks