Postman – Whether it is a developer, a tester or a business analyst when it comes to test the API’s, the very first thing that comes to our mind is Postman client.It is light weight, easy to install and easy to use.
Considering that you’re very much aware of the tool, we will directly jump to our main topic i.e., how to automate API’s using Postman?
Prerequisites :-
- Install Chrome Browser.
- Add Postman plugin to your browser.(By default it will install the latest plugin)
Once you install, it looks something like below.
Things to understand before we start writing our scripts. Numbering given in the image and its explanations are as follows
- Collections – Group your requests in a single folder. Easy – to maintain, to track & to execute.
- Interceptor – It is a chrome extension used to manipulate the requests between Postman client and web-servers. Enabling Interceptor will share the cookies among all the subsequent requests.
- Sync Data – Create a Postman account and make sure to Sync always so that you will have a backup in future.
- Sign In – To perform #3, you need to create an account and login first. Creating a postman account will also help in sharing your collections to rest of the team members.
- Environments – For every collection you create, you can have a environment created for it. These environments will have all the variable like, global or environment specific variables used for your collection to run.
- Settings – Here you can actually set/import/export/share/delete the global or environment variables. You can set these variables either manually or use set methods in pre-request-script section or in tests section.
- Tests – In this area, all the assertions, validations and test cases are written.
Now we will discuss what actually are these variables and what are the different types we have.
Variables are used to store your dynamic data and can be re-used for subsequent requests. It helps to keep your code clean. How? Keep reading.
Postman supports four different variables:
- Global variables.
- Environment variables.
- Logging variables.
- Data variables.
When to use these variables and what is the scope of these variables?
Global Variables :
When you want to make use of a variable irrespective of environments then set that variable as global variable using below set method. In short, Global variables can be accessed broadly regardless of the selected environment.
Set Global variable :
1 |
postman.setGlobalVariable("variableName", "variableValue"); |
Get Global variable :
1 |
postman.getGlobalVariable("variableName"); |
Environment Variables :
When you want to create a variables, specific to that environment or you want to over-ride global variable value to a specific value only for this specific environment then make use of environment variables. In short, Environment variables can be accessed with the corresponding environment template.
Set Environment variable :
1 |
postman.setEnvironmentVariable("variableName", "variableValue"); |
Get Global variable :
1 |
postman.getEnvironmentVariable("key"); |
Logging variables :
Logging variables are mainly used for debugging purposes. When you send a request, after evaluation, the value of that variable will be logged into postman console. Just insert below line in your code.
1 |
console.log(variableName); |
Data Variables :
When you want to make use of values from a csv or a json file like firstname & lastname then import the file into the postman and postman will use these data variables from the file given.
Sample json file uploaded :
1 2 3 4 5 6 7 |
{ data: { "firstName" : "abc", "lastName" : "xyz" } } |
then you can make use of these values in your pre-request-script or in tests as follows:
1 2 3 |
console.log("using first name from the file" , data.firstsName); console.log ("using last name form the file" , data.lastName); |
Here data is an object which holds the values. To get the particular object property value use data.propertyName i.e., data.firstName.
If you want to make use of these values in URL parameters then write the property name in double curly braces i.e., {{firstName}} or {{lastName}} which will resolve and fetch the values of firstName and lastName as abc & xyz.
Enough theory now. Lets start the execution flow.
We will take an example here to automate an account creation POST, GET, PUT, GET(to verify updated values) & DELETE
Sample API end point to create an account :
1 |
https://test-sample.automation.com/account |
URL is something which every request needs, it is common so why to write it for every request? we can make use of variables right? Yes!! we will create a variable and store the URL as a variable value and we will make use of that variable name in our request.
1] Navigate to Manage Environments by clicking settings(gear icon)
2] After clicking, Manage Environments option, you will be displayed below window.
3] Click Add and below window will be displayed. Enter the environment name(Test-Env), variable name(URL) and its value(https://test-sample.automation.com) to set and click ‘Add’ again.
4] A new environment is created and inside it, variable URL is saved successfully.
5] Select the newly created environment for your collection to run.
Now, the URL variable holds the value and hence, we can directly use that variable in our request.
1 |
{{URL}}/account - where URL holds the value i.e., https://test-sample.automation.com |
1. POST Request:
To create a account, we need account details so below is the sample json body we will be using.
1 2 3 4 5 6 |
{ "username" : "test", "email" : "test.sample@gmail.com", "firstName": "sample", "lastName" : "user" } |
We may need to verify the account details in future right? So we will store these values in environment variables and will make our code reusable. This time, instead of creating variables manually, we will set it via code in ‘pre-request-script’ section like below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Request 'Pre-request-script' goes like this postman.setEnvironmentVariable("username", "test"); postman.setEnvironmentVariable("email", "test.sample@gmail.com"); postman.setEnvironmentVariable("firstName", "sample"); postman.setEnvironmentVariable("lastName", "user"); Request 'Body' goes like this { "username" : "{{username}}", "email" : "{{email}}", "firstName": "{{firstName}}", "lastName" : "{{lastName}}" } |
Once you execute the script, these values will be resolved and will be used in the body to execute the ‘Create User’ request and along with it, these variables will be set as environment variables(refer below image) which can be used in later stages for validations.
Now, we are left with ‘Tests’ section . Once the request is executed, we will be getting its response with Success message & accountID(‘data’ in below code) something like below.
1 2 3 4 5 6 |
{ "status": "SUCCESS", "message": null, "error": null, "data": "123454321" } |
To verify that the request is processed successfully, in the Tests section we will write couple of tests so that we can validate once request is executed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
tests["Status code is 200"] = responseCode.code === 200; 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"); } tests["Response Body matches string SUCCESS"] = responseBody.has("SUCCESS"); var jsonData = JSON.parse(responseBody); postman.setGlobalVariable("accountID", jsonData.data); |
Above code has 4 tests.
1.
1 2 3 |
tests["Status code is 200"] = responseCode.code === 200; To verify the status of the request. Is status code is 200? |
2.
1 2 3 4 5 |
var contentTypeHeaderExists = responseHeaders.hasOwnProperty("Content-Type"); tests["Has Content-Type"] = contentTypeHeaderExists; To verify whether the content-type is provided or no. |
3.
1 2 3 4 5 6 |
if (contentTypeHeaderExists) { tests["Content-Type is application/json"] = responseHeaders["Content-Type"].has("application/json"); } To verify the value of the content-type given i.e., application/json in our case. |
4.
1 2 3 |
tests["Response Body matches string SUCCESS"] = responseBody.has("SUCCESS"); To verify the string "SUCCESS" in the response. |
Postman UI of ‘Tests’ section will be something like below:
and clicking ‘Send’ button, the result of the tests will be something like below:
Along with this, the last two lines of code is written to store the accountID as global variable(purposely making it global instead of environment variable ) and use it for future purposes.
1 2 3 |
var jsonData = JSON.parse(responseBody); postman.setGlobalVariable("accountID", jsonData.data); |
which will set the accountID as global variable and can be re-used for future requests.
2. GET Request :
URL goes like this :
1 |
{{URL}}/account/{{accountID}} |
We stored the accountID in a variable and we are using the same variable as input to our GET request.
Request ‘Test’ section goes like below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
tests["Status code is 200"] = responseCode.code === 200; tests["Response Body matches string SUCCESS"] = responseBody.has("SUCCESS"); var jsonData = JSON.parse(responseBody); tests["Success --> Request & Response accountID matched"] = jsonData.data.id == postman.getGlobalVariable("accountID"); tests["Success --> Request & Response username matched"] = jsonData.data.username === postman.getEnvironmentVariable("username"); tests["Success --> Request & Response account Email-ID matched"] = jsonData.data.emailId === postman.getEnvironmentVariable("email"); tests["Success --> Request & Response account First name matched"] = jsonData.data.firstName === postman.getEnvironmentVariable("firstName"); tests["Success --> Request & Response account Last name matched"] = jsonData.data.lastName === postman.getEnvironmentVariable("lastName"); |
Click ‘Send’ & Response of the request will be as follows :
1 2 3 4 5 6 7 8 9 10 11 12 13 |
{ "status": "SUCCESS", "message": null, "error": null, "data": { "id": "123454321", "username": "test", "emailId": "test.sample@gmail.com", "firstName": "sample", "lastName": "user", } } |
Result of the tests will be as follows :
3.1 PUT Request :
PUT request URL goes like this:
1 |
{{URL}}/account/{{accountID}} |
We stored the accountID in a variable and we are using the same variable as input to our PUT request.
Request ‘Pre-request Script’ goes like this:
1 2 3 4 |
var rnd = Math.floor((Math.random() * 10000) + 1); var name_update = postman.getEnvironmentVariable("firstName")+rnd; console.log(name_update); postman.setEnvironmentVariable("firstNameUpdated", name_update); |
Request ‘Body’ goes like this:
1 2 3 |
{ "firstName": "{{firstNameUpdated}}" } |
Request ‘Tests’ goes like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
tests["Status code is 200"] = responseCode.code === 200; 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"); } tests["Response Body matches string SUCCESS"] = responseBody.has("SUCCESS"); var jsonData = JSON.parse(responseBody); tests["Success --> Request & Response account ID matched"] = jsonData.data == postman.getGlobalVariable("accountID"); |
Click ‘Send’ & Response of the request goes like this:
1 2 3 4 5 6 |
{ "status": "SUCCESS", "message": null, "error": null, "data": "123454321" } |
Test results goes like this:
3.2 GET Request (to verify updated user details)
URL goes like this:
1 |
{{URL}}/account/{{accountID}} |
Tests section goes like this :
1 2 3 4 5 6 7 8 9 |
tests["Status code is 200"] = responseCode.code === 200; tests["Response Body matches string SUCCESS"] = responseBody.has("SUCCESS"); var jsonData = JSON.parse(responseBody); console.log(postman.getEnvironmentVariable("firstNameUpdated")); tests["Success --> Request & Response account first name matched"] = jsonData.data.firstName === postman.getEnvironmentVariable("firstNameUpdated"); |
Click ‘Send’ & Response body will be as follows :
1 2 3 4 5 6 7 8 9 10 11 12 13 |
{ "status": "SUCCESS", "message": null, "error": null, "data": { "id": "123454321", "username": "test", "email": "test.sample@gmail.com", "firstName": "sample4321", //firstname + rand "lastName": "user", } } |
Tests output are as follows :
4. DELETE Request:
URL goes like this:
1 |
{{URL}}/account/{{accountID}} |
Tests goes like this:
1 2 3 4 5 |
tests["Status code is 200"] = responseCode.code === 200; tests["Body matches string SUCCESS"] = responseBody.has("SUCCESS"); tests["Body matches string removed successfully"] = responseBody.has("removed successfully"); |
Response goes like this :
1 2 3 4 5 6 |
{ "status": "SUCCESS", "message": null, "error": null, "data": "sample4321 removed successfully" } |
Tests output goes like this:
Now all our POST, GET, PUT & DELETE requests test cases are passing and now we will run our collection once, to see the result.
- Below highlighted are the set of 5 requests within a collection called TEST.
2. Click the arrow and click ‘Run’ button.
3. Clicking ‘Run’ button will open a new window as below.
4. Click ‘Run Test’
5. Check the number of test cases passed and failed and if you want, you can download/export the test run with results as a json file too as shown below.
Done. Congratulations!! You just learnt how to automate API’s using POSTMAN.
Before I close this topic, below are some of the key points to remember.
- Make sure to enable interceptor always.
- Make sure to enable Sync by logging into the Postman.
- If a variable from the currently active environment shares its name with a global variable, the environment variable value will take priority. In other words, global variables are overridden by environment variables, which are overridden by data variables (only available in the collection runner).
- Variables are shown in orange color and hovering on it will show the value and scope of that variable.
References :
https://www.getpostman.com/docs/
This sounds good in practice. But Postman does not let you delete cookies in these automated tests. One has to manually delete the cookies. This makes Postman unusable for most people.
If you have a way, Please let me know. I could not find a solution.
Apology for the late reply and thanks for commenting. Yes, that is true that we cannot delete cookies by scripts, we have to delete cookies manually only but this is how I solved this problem.
In my project, we have an API called ‘Impersonate API’ that takes the username and password as input(part of the request body), and the API returns the cookie in the response header if the username and password match. My use case is, we have some APIs only admin can access so I use this impersonate API to get the admin cookie by giving admin username/password and verify(200 status) the subsequent requests. Later, I will call the same API with regular user credentials and verify(401 Unauthorized) the subsequent requests. If you have such APIs in your project then you can try something like this.
I Will let you know if I can find something around this in the future, my friend.
Hi Vyasaraj ,
Great Instructions! Thank you! Is the site still working? I sent a request to http://test-sample.automation.com and I am getting this mesage back and cannot connect.
Could not get any response
There was an error connecting to https://test-sample.automation.com/account.
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
Proxy configured incorrectly
Ensure that proxy is configured correctly in Settings > Proxy
Request timeout:
Change request timeout in Settings > General
The URL I used in my blog is a sample URL so you’re not getting any response. Please use a valid URL or the URL of some application used in your project. By the way sorry for the late reply and glad that you liked my blog.
Wonderful works @Vyasaraj V.
Thanks my friend.
Hello. Firstly, I would like to thank you for your valuable information on API automation using POSTMAN.
I would like to automate API using POSTMAN for multiple values (parameters). For example, there is a API to create account and I want to create 100 accounts by passing the parameter values like First Name, Last Name, Age and so on. Is it possible to fetch these parameter values from excel sheet or something? Please advise.
Ah!! Sorry, I missed your comment. Let me know if you’re still looking for this will provide you some solution.
My friend, I am glad that you liked my blog.Thank you. 🙂
Hey there, Saved ass a favorite!! I really enjoyed your web
site!! Cheers for the article!!
Glad you liked it. Thanks
Good Work | We have also some nice stuff you can visit my website higherpositions.com
http://www.higherpositions.com/
Great tips, many thanks for sharing. This information is useful for us. keep it up!!
Awesome! Thanks for taking the time in giving feedback.