API Testing with Postman- Part 1- Setup

Khemlall Mangal
15 min readFeb 18, 2022

--

All, lets learn api testing with postman. Learn along with me while i jot down pointers to make this smooth and quick read.

Pre-requisite:

POSTMAN — https://www.postman.com/downloads/

Git Bash — https://git-scm.com/

Clone Api Repository- actual api to work with — https://github.com/taylonr/postman

NODEJS: Install Node js on your machine

So lets Download the Repo

Step 1: open up git bash -> create a folder and name is postman in c:/postaman for example….

step 2: In Git bash navigate to that folder (window used cd and folder location)

Step 3: Git Clone so copy the clone link — Learn how to clone repository …In our case, we will just download the code and move it to the folder you just created.

Run the following command
git clone https://github.com/taylonr/postman.git

Run NPM Install Once completed

Run the following command : $ npm run start:dev

Now go to your browser → lets localhost:3000/landing

You are all set up now!

Lets now Dive into learning about Testing API. We will do this on the Dev point of view and QA point of view….Welcome!

In order to access the api you need to pass in the token. See info below.

Go to postman -> click header -> add token

you should now see:

We have option to Search so URL

localhost:3000/books/search?title=waste

In Get Request enter url: localhost:3000/books/search then click params and enter params, it will then transform to above url with data.

You can add multiple parameters and postman allows you to include or exclude parameters by clicking a box.

Another feature of Postman is that it allows you to download the response.

Postman Basic Environment

What if you need a different value of preset header based on the environment you have. You could have local, develop, staging, production, or some other environment and each may need a different value. How do we handle that in Postman?

Alright, let's first startup our test server and explore this scenario further.

Run: npm run start: dev

Now notice we have Test on Port: 3030 and dev on Port 3000.

What if you want to run your test for the two different environments but you don’t want to keep typing the localhost:3000 or ocalhost:3030 in the URL every time you want to test against the different environment.

Introducing Environment

Click on Environment -> + (create environment)

Enter the name of the environment, lets call it dev and define the host as the variable name and then add the value entry

Next lets duplicate that and add a new variable QA

As you notice we have two variable DEV and QA with different host value.

Now how do we utilize this environment?

Ok lets first change our URL to be {{host}}/books etc ….On the drop down under environment select the environment you want o use.

Notice the response id will be different for the different environments in our reponse. So that this how you can manage environment. If you want to see what value you have in the environment you can click on the Eyeball and you will be able to see the variable and value.

Let's talk about IMPORT UTILITY in postman.

Navigate to http://localhost:3000/ui

You should see something like this:

Now let's talk about the import feature and watch it in action. It allows you to make API call to help set up data

Let add the following below and open up your chrome debugger and choose network tab to see the request

Submit the request

Right-click and select copy as cURL as bash

Click Import button

Select RAW Text and paste the curl request and click continue

Notice we have the request built out for us along with the header and body etc

So this is one way you can copy the request from UI and get it to postman and test your request.

Another Tool in Postman we will talk about next is PROXY.

It allows you to specify which port the proxy will run on and where to store the request….

Lookup the IP address for your computer → Ony any device you are monitoring you can set up a proxy by adding the computer id to the proxy.

Once you setup the the proxy and navigate to the link, you will be able to get or see the request coming in and you will get the request along with header etc. This feature allows you to be able to trouble shoot a request coming in from any device. We are not going to go into details on this but its something you need to be aware of and will find it useful in your day to day api automation efforts.

Generating Code, Lets talk about Writing a code by leveraging Post man. If you want to get the code for the following request for example

There are many other language snippet available that will make it easier and nifty for you to write your code.

Another Feature or utility is postman ability to sync request. You will see option to sign in this will automatically sync accross multiple computers. Very helpful where you can see request and history of all request.

These are some great feature of postman.

Part 2: Testing API

In this lesson we will walk though testing. The easiest way to get started in postman is to use the pre-built test provided by postan. Start by making a requst to localhost:3000/books which brings back the same data you had seen before.

Now lets create our first Test -> go to Test

on the Right is some snippet. if we want to test the status code coming back from this api, we can select status code and it will provide a snippet to test status code 200 for example.

Basic of Testing — Pre-built Test.

If you click send again you will now notice you have 1/1 test ran and pass.

Lets add another test and use another snippet. Select status code name has string

Notice that when you click send you now have two tests and 1 pass and 1 fail. The response expected was OK but it got created.

Lets change this now in our test to OK and re-run. Notice it passed.

Lets examine our test and understand each part of the syntax.

pm — This is an object that give you access to everything you need to create tests. Think of it as postman name space.

The first function is the Test Function. This function will take two parameter, test name (description) followed by the function that should be executed for the test.

This function will take two parameter, 1 the test name. Example status code is 200. You can name your test what ever you want that make sense to your team for testing the functionality.

Next is the Function that should be executed for the test. This function takes no property.

PM object has INO, GLOBALS, ENVIRONMENT AND ASSERTION available to you. Check out docs for more details. https://www.getpostman.com/docs

Now lets Write our own Basic Test.

Let write a test that check that the get request localhost:3000/books return 5 books for example. We will expand this example to touch on topics incrementally.

Lets go back to where we left off and lets create a new test under the first two we created.

Lets start by typing pm.test and give it a name in this case we can say returns 5 books right.

pm.test(“returns 5 books”, function () {

});

Next lets create a

pm.test(“returns 5 books”, function () {

const books = pm.response.json(); — This will hold the response in the books variable

pm.expect(books.length).to.eql(35);

});

If you run your test again you will notice the test is passing but there is a caviat here..and this is where we will be spring boarding from to the next topic to improve this test while introducing new functionality and solutions.

Checking the lenght on this test is not really great as this value can change. You can expect 35 now but we could have more or less book in the next test run as someone may add new book or delete etc.

So let check something that will always be true. So for example every book will have a title define. So i think that will be the best thing to change.

Let create a new test called All books should have a title

pm.test(“All books should have a title”, function(){

}

Then define books to have the response and now create a new function that will expect all item in the array should have a title and should not have a title undefine.

pm.test(“All books should have a title”, function () {

const books = pm.response.json();

pm.expect(books.every(books => {

return books.title !== undefined;

}))

Now test and it should pass

Lets start taking about Collections in POSTMAN.

Let create a household list feature. So we have a feature is to get all the items on all wishlist for all the users in a single household. There has to be a collection of books, there has to be users and user has to be apart of a household and the user needs wishlist and the wishlist aren’t empty they have books on them.

Let make a request post to localhost:3000/households

Remember you need to pass in the G-TOKEN

Now this time we will click save → enter request name → click new collection and then enter name and click create

notice we now have a collection with 1 request

Now everything is save. First request let create a post and create a new user.

The user will take email, first and last name and householdid

Example:

{“email”: “khemlall.mangal#gmail.com”,“firstName”: “khemlall.mangal#gmail.com”,“lastName”: “khemlall.mangal#gmail.com”,“householdid”: 1}

Create a Post request: (add your preset for G-TOKEN header)

Once you submit your request you will get the following:

Now save to your household wishlist

Next, let create another request to add books to a user wishlist
so my wishlist id was 38 so we will go to localhost:3000/wishlist/{wishlistid}/books/{bookid}

(POST) localhost:3000/wishlist/38/books/1 don’t execute this just save it to the collection. we will use it soon

Add another request (get)

localhost:3000/households/1/wishlistBooks

So when you are done you should get something like this:

Now lets create second user and add a book to that second user in the household. Just right click on the request and duplicate and rename with adding a different user…example:

{"email": "rpersaud23@gmail.com","firstName": "rohini","lastName": "mangal","householdid": 1}

Do the same for add book to second user. example

localhost:3000/wishlist/39/books/2

Now you can click on each individual request in the household wishlist and execute each one. But that not efficient. Introducing Collection Runner.

COLLECTION RUNNER

Click on ellipse → run collection

Run collection

This will give you the option to run the collection you can uncheck which one you dont want to run etc….but this will automate the way you run the collection rather than just run it manually one by one.

You will now notice it runs successsfully.

Now, we have you do this purposely to see that running this will need some more tweaking.

First go and try to find all your users. You will notice that there is duplicate and if you go to that user you will see there is empty book associated with that user and wishlist. you will notice that wishlist ID is hardcoded.

So let introduce Variable to ensure the script is using right value for the request.

How to use postman to programmatically update your request script so that the data is setup correctly.

Run the Household request again note the ID → Test → set global variable

Now lets set our Global variable….You will see somethign like this:

pm.globals.set(“variable_key”, “variable_value”);

Replace with

pm.globals.set(“householdId”, pm.response.json().id);
householdid now have the value

Next, lets take the householdid and replace it in each request. You will surround the householdId with curly braces like this: {{householdId}}

CreateUser:

“email”: “khemlall.mangal#gmail.com”,“firstName”: “khemlall.mangal#gmail.com”,“lastName”: “khemlall.mangal#gmail.com”,“householdid”: {{householdId}}}

Now lets go though each of the request and create our parameters and use them.

pm.globals.set(“firstwishlistid”, pm.response.json().wishlistId);

Seconduser

pm.globals.set(“secondwishlistid”, pm.response.json().wishlistId);

Add book to user

localhost:3000/wishlist/{{firstwishlistid}}/books/1

Add Second book to user

localhost:3000/wishlist/{{secondwishlistid}}/books/2
add second book to wishlist

Get household books

localhost:3000/households/{{householdId}}/wishlistBooks

Now once you have setup the variable let re-run the collection but this time ensure you check the save responses.

run collection

Once its completed you can click on get household books and be able to see the response body

Next thing remain hardcoded is the URL. Now lets variablize this.

URL can differ based on the environment that we are testing on. QA DEV PROD ETC. Earlier we setup environment different environment with the variable host….now lets just change that now.

Example:

Do this for each url.

PRE-REQUEST SCRIPT

In testing you know that we need to have a setup and a teardown to basically do a set of actions before we start the test and maybe make some configuration changes etc and then tear those down. Setup data etc ….

Say you want to setup some random user before you run, you can use the prerequest script

Example:

const users=[{"email": "khemlall.mangal#gmail.com","firstName": "khemlall","lastName": "mangal"},{"email": "khemlall.mangal#gmail.com","firstName": "rohini","lastName": "mangal"},{"email": "khemlall.mangal#gmail.com","firstName": "kalawaite","lastName": "mangal"},{"email": "khemlall.mangal#gmail.com","firstName": "geta","lastName": "permanand"}];const user = _.sample(users);pm.globals.set("email", user.email);pm.globals.set("firstname", user.firstname);pm.globals.set("lastname", user.lastname);

In our request body we can now use the variable

{
"email": {{email}},
"firstName": {{firstName}},
"lastName": {{lastName}},
"householdid": {{householdId}}
}

Other topics to come:

Datafile

Download the following Datafiles for practice in this section.
https://drive.google.com/drive/folders/1ZU4ptoUzZ57LHpPEtFRik6cxmeFUcusM?usp=sharing

We can use datafiles to create a list of user for example. Postman gives us the neat functionality to use datafiles to create our data.

Here is an example:

  1. Create a New collection called “create Books”… By now you should know how to create a collection, if you have forgotten please refer to the section above.
  2. Add a Post request to : {{host}}/books
  3. Add your Preset Header
  4. Add the following raw body:
{
"title": "{{title}}",
"author": "{{author}}",
"isbn": "{{isbn}}",
"publicationDate": "{{publicationDate}}"
}

Notice the above request is surrounded with the {{}} which we have said is telling postman to look for the title, author etc in the file……

5. Go to run collection → Choose 4 Iteration → select file under Data

Choose the file you downloaded above downloaded and execute.

Once completed you should see that we have 4 books created from the file.

Initialize Test Data with postman

We want to setup our data in a way to reduce duplication and intialize your test data. Instead of adding a request for every single user you want to create and have post script the number of user to create.

The flow will be we setup some variable that will have the number of user we want to create and then add books and clean up script at the end.

Let go back to our household wishilist colletions.

Let go into our pre-request script section

pm.globals,set("numberofUsers",2);pm.globals,set("currentuserCount",0);pm.globals,set("numberofWishlistAdds",4);pm.globals,set("currentwishlistCount",0);pm.globals,set("wishlistIds",[]);const getbooks ={url: 'http://${pm.environment.get("host")}/books',method: "GET",header: "G-TOKEN:ROM831ESV"}pm.sendRequest(getbooks, function(err, books){const ids = _.map(books.json(), function(book){return book.ids;});pm.globals.set("bookIds", ids)})

Refactor: loop over user

Refactor: loop over wishlist

Scenario: Teardown

Running your refactored collection

Executing test

Testing from Command Line

MOCK SERVER
Mock server what is it

faking out data

creating your first mock

additional responses

mocking a feature

mocking reponse codes

Postman matching algorith

DOCUMENTATION

Reference:
Course:
Postman Fundamentals on plural sight —
integrating your test with CI system (Jenkins)

Please note that the info provided here is from a course I took on Pluralsight and had made notes for myself and others for reference. I am not the owner of the repository etc i just use this as per the course and added it here for learning purpose.

--

--

Khemlall Mangal

I am a passionate coder, QA Engineer, and someone who enjoys the outdoors.