How to write automated tests for APIs with Postman – Part 2

In the last tutorial we discussed how to set up Jetpacks and write a basic test for a sample API endpoint. The test checked the response status code and the Content-Type header against known values.

In this tutorial, we'll write a more comprehensive test. We'll use the super-useful JSONBlob API. This API lets you create, update, and delete content on the server. We'll use it to mimic a blog. This mirrors common API usage scenarios and will be helpful in demonstrating how Postman can make things easier for you.

Do remember that the API is only for demo purposes and does not follow the best security practices.

1. Create an environment

In this tutorial, we'll use environment variables. Create an environment with the following values:

url: https://jsonblob.com
Screen Shot 2016-06-27 at 16.46.44

Select the environment in the environment list to activate it. We'll use test scripts to fill this environment with more values.

2. POST request to create a new blog post

To create a new blog post, we'll need to send a POST request to {{url}}/api/jsonBlob with the following request body:

Screen Shot 2016-06-27 at 18.50.07

This endpoint will return a "Location" header, with the URL of the newly created blog post:
Screen Shot 2016-06-27 at 16.49.24

Let's use the test script feature to extract this header and store it:
Screen Shot 2016-06-27 at 16.49.31

Save this request to a collection.

3. Validate that the post was created
We can now make a GET call to the saved URL to make sure the blog post was created. Set the URL to {{blogLink}}, and add a test script to validate the contents.
Screen Shot 2016-06-27 at 17.39.57

4. Update the blog post

We can update existing blog posts using the PUT method. Set the URL to {{blogLink}}, since we know the blog post we want to update. Let's update the blog content to:

Screen Shot 2016-06-27 at 18.20.31

5. Verify that the contents have been updated

We can use a modified version of the GET request we created in step 3. All we need to do is change the test script to:

Screen Shot 2016-06-27 at 17.39.53

6. Delete the blog post

Change the GET to DELETE to remove the blog post from the server.
Screen Shot 2016-06-27 at 16.57.27

7. Verify that the blog post has been deleted

Now that we've deleted the post, let's verify that the blog URL no longer returns any content. Use the same URL as the previous GET requests, and change the test script to

A 404 response code indicates that the entity we requested was not found.
Screen Shot 2016-06-27 at 16.57.30

Running the request says that everything went well. Postman would notify you of errors if something did not go as per expectations. To check for Javascript errors in your code, you can open the Chrome Console and monitor the logs.

You can download this collection here.

In the next tutorial, we'll look at the collection runner and how we can run this entire collection in one click using the Collection Runner.

The "How to write automated test with Postman" series

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

33 thoughts on “How to write automated tests for APIs with Postman – Part 2”

  1. Have recently started using this tool and find it really good. Very lightweight and easy to use. I was hoping to be able to build it into our existing test automation system. Currently I run the api test locally on my mac against the desired environment but I was hoping to be able to build it into our existing test automation system. Currently we have rspec/capybara integration tests that are run via Jenkins hosted on an ubuntu machine. I would like to have the api tests ran via a Jenkins job also, and on successful completion of this job it would kick off the other rspec/capybara integration jobs. Is it possible to use this tool via Jenkins?

      1. Does postman let you load different tests cases?

        – we'd like to define all the endpoints once,
        – define multiple variations of data used in various scenarios against those endpoints
        – define multiple variations of tests.

        A simple example is:
        – posting valid json to an endpoint, expected result here is 200
        – posting invalid json to the same endpoint, result here should be 40x and particular response.body

  2. II have a scenario where i need to login in order to fetch the cities list but where i need to run a login api by which i will be getting user_id and token and these data i'll be putting up in fetchcitieslist api where i'll be getting up the list for the particular user_id, but when i am trying to follow the above steps i am not able to do so, Could you please help me out

      1. I guess the question was:

        Is it possible to execute Login before all other test(folders)?

        Like this:
        – Login and obtain token and user_id. Put it into environment variable {{token}} {{user}}
        – Use it in all other tests (Authorization header)

        In runner it's not possible to select order of folder, so I did like this:

        – Posts (folder)
        – – Login
        – – Create post
        – – Edit post
        – – …

        – News
        – – Login
        – – Create news
        – – Edit news
        – – …

        So login should be inside each folder. (Also with this approach it's possible to execute one folder on test)

  3. Hi,
    I have a query how can we validate Json response that no additional attributes are coming in response body.

  4. Hi, I tried to capture JSON response in a Variable and i am getting the values as undefined in the environment variable.
    var data = JSON.parse(responseBody);
    postman.setEnvironmentVariable("user_id", data.userid);

    1. You might have already figure this out – but if I have to guess then userid might be in an array and if this is the case then this is how you should capture it's value in environment variable.

      var data = JSON.parse(responseBody);
      postman. setEnvironmentVariable("user_id", data.nameofarrayfromresponse[0].user_id);

  5. How to use loop inside the POST-Body (When I do need to post, I need to change the reference id which has to be unique number every time I post. Now since I am running Automation using jetpacks, i need to use loop so that one post can run 5 times but with different reference id)

  6. Hi, running collections as url on batch command at jenkins. Like this "newman -uhttps://www.getpostman.com/col… -e TEST.postman_environment -g globals.postman_globals –stopOnError" but i can not see to fail cases on jenkins's console output. its look like all of them passed but one case must be fail.

  7. What if my authorization request must contain encrypted password (encryption uses session id received in a previous request). Is there a way in Postman to do RSA encryption in the pre-request script?

  8. how to extract the content of json and set it to global variable?
    for example my output will be something like this

    { "status": 200
    "message" : "{"my_token": "XYZFKDFJIDSLDSDNUFBDB", "Url":"0.0.0.0"}"
    }

    Now in this output I am interested in my_token and I wanna set it to postman global variable in order to test my remaining cases using the global variable.

    can anybody give me JAVA_SCRIPT for the above requirement?

    1. try this :
      var jsonData = JSON.parse(responseBody);
      postman.setEnvironmentVariable("AccessToken", jsonData.message.my_token);

      have AccessToken in your env variable.

  9. Json response:
    {
    "detail": "Method "GET" not allowed.",
    "exception": "Method "GET" not allowed.",
    }

    How can I verify this test?
    I have tried this test, but it failed
    tests["detail: Method "GET" not allowed."] = responseBody.has("Method "GET" not allowed.");

  10. Step 2 states "This endpoint will return a "Location" header, with the URL of the newly created blog post:" but I don;t see any Location attribute returned, hence by

    my attempt to validate that the post was created in Step 3 is failure (presumably because the test in Step 2 never actually retrieved and consequently set this header into the blogLink variable.

    Any guidance on how this can be rectified would be appreciated

  11. I'm unsure how to loop through my response to set an environment variable. My response looks like this:

    {
    "Items": [
    {
    "ResourceType": "EntityState",
    "Id": 370,
    "Name": "Open"
    },
    {
    "ResourceType": "EntityState",
    "Id": 371,
    "Name": "In Progress"
    },
    {
    "ResourceType": "EntityState",
    "Id": 372,
    "Name": "Done"
    }
    ]
    }

    I want to store the ID 372 from the state that is "Done"
    Any ideas?

  12. This is how a self article should be guys..

    Kudos to you all for developing a nice and simple tool and this working example.

    Thanks,
    Gaurang

  13. I've tried to fix all these 4 options but still getting the error:
    Could not get any response
    There was an error connecting to https://jsonblob.com/api/jsonBlob.

    Why this might have happened:
    The server couldn't send a response:
    Ensure that the backend is working properly
    Self-signed SSL certificates are being blocked:
    Fix this by turning off 'SSL certificate verification' in Settings > General
    Client certificates are required for this server:
    Fix this by adding client certificates in Settings > Certificates
    Request timeout:
    Change request timeout in Settings > General

    1. Thanks for getting in touch. I think your best bet would be to join our Slack community and post your question there, here is a link to join: https://www.getpostman.com/slack-invite. It's a great resource for all Postman users, you'll even find our very own devs on there all the time. Let me know how you get on.
      Cheers,
      Rob

Leave a Reply

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