Postman API Automation Script and integrate with Jenkins Documentation
Published: 2022-11-08 04:42:10

**<u>Step 01</u>**: First create a API collection in Postman.
**<u>Step 02:</u>** Create Environment to store base URL, Auth token and other necessary key value. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5bpjdlena6ekyr07vfmh.png)

After that select environment before check the API response.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i4bjw5m4f0gb8bs5tnzn.png)

**<u>Step 03:</u>** Instant of create an Environment can also store Base_URL in API collection variable or as a global variable.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wm5nu7bzwd7uowoab8e4.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/18319qca8y47gib8zgki.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lp5ajrj5ifylscoztgbk.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rqmfh3ku5vp2dqc6tt4v.png)

Click on "Add new variable" and then set Scope.Thats all

**<u>Step 04:</u>** Store any kind of Dynamic data like - Auth token or Bearer token add this two lines of code on API collection Test scripts.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mp5w921np82b8kbat7ud.png)

```
var response = pm.response.json();
pm.environment.set('access_token',response.data.access_token);
```
And store token in collection variable section or global variable section **<u>(Follow step - 03)</u>**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0nzzdmosnzdvey9glj1r.png)

For store any array value Simply reference an individual element of an array using the array name and the index inside parentheses, then use the assignment operator (=) followed by a value.

```
var response = pm.response.json();
pm.environment.set('access_token',response.data.access_token);
pm.environment.set('user_key',response.data.user[0].user_key);
```

**<u>Step 05:</u>** After that i prefer write API test cases. For Test case i used - [Qase](https://app.qase.io/projects).
Mainly API test case focus on BUSINESS LOGIC and we handle For Test case i follow this documentation -
[Test case and requirment](https://documentation.tricentis.com/qtest/od/en/content/manager/requirements_and_test_design/using_apis_to_link_test_cases_and_requirements.htm)

**<u>Step 06:</u>** When I test a API Manually i focus on those check points.

1. Keys verification. If we have JSON or XML APIs we should verify that all the keys are coming. For example we focus on the UI screen.
2. Have a test case to do XML, and JSON Schema validation.
3. Verify the Parse the Response data
4. Verify the JSON Schema validation, Verify the Field Type, 
   Verify the Mandatory Fields
5. Valid Response headers & Negative Test Cases response
6. Verify how the APIs error codes are handled.
7. Verify the response HTTP status code.
8. Valid Response payload
9. Chaining Request verification.
10. Verification of APIs with Data parameters.
11. End to End CRUD flows
12. Database Integrity Test Cases
13. File Upload Test Cases

**<u>Step 07:</u>** For postman scripting i mention some common test scenario script.

For GET API -> Check 200 response and 404 response

<u>Script 01 - </u>

```
pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});
```

<u>Script 02 -</u>

```
pm.test("Status code is 200 ", function () {
    pm.sendRequest('https://dummyjson.com/products/1', function (err, res) {
        pm.expect(err).to.not.be.ok;
        pm.expect(res).to.have.property('code', 200);
        console.log(res.json())
    });
});
```
<u>Script 03 -</u>

```
pm.test("Status code is 404", function () {
    pm.sendRequest('https://dummyjson.com/products/one', function (err, res) {
        pm.expect(err).to.not.be.ok;
        pm.expect(res).to.have.property('code', 404);
        pm.expect(res.json().message).to.eql("Product with id 'one' not found");
        console.log(res.json())
    });
});
```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k6tvbx60816ixjguaat7.png)

For POST API -> Check 200 response and 404 response

**<u>Script 01</u>**

```
//Successful Add Product
const postResponse = {
  url: 'https://dummyjson.com/products/add',
  method: 'POST',
  header: {
    'Accept': '*/*',
    'Content-Type': 'application/x-www-form-urlencoded',
  },
  body: {
    mode: 'urlencoded',
    urlencoded : [
      { key: 'title', value: 'Apple Magic Mouse'},
    ]
  }
};

pm.test("Test-01: User successfully add Product", function () {
    pm.sendRequest(postResponse, (error, response) => {
        pm.response.to.have.status(200);
        console.log(error ? error : response.json());
        });
});
```
**<u>Script 02</u>**

```
/Failed to Add Product
const addProductFailResponse = {
  url: 'https://dummyjson.com/products/add_product',
  method: 'POST',
  header: {
    'Accept': '*/*',
    'Content-Type': 'application/x-www-form-urlencoded',
  },
  body: {
    mode: 'urlencoded',
    urlencoded : [
      { key: 'title', value: 'Apple Magic Mouse'},
    ]
  }
};

pm.test("Test-02: User Failed add Product", function () {
    pm.sendRequest(addProductFailResponse, (error, response) => {
        pm.expect(response).to.have.property('code', 404);
        pm.expect(response).to.have.property('status', 'Not Found');
        console.log(error ? error : response);
        });
});

```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hipyp16w92putpd0bstp.png)



For PUT API -> Check 200 response and 404 response

**<u>Script 01:</u>**

```
//Successfully Update Product
const postResponse = {
  url: 'https://dummyjson.com/products/two',
  method: 'PUT',
  header: {
    'Accept': '*/*',
    'Content-Type': 'application/x-www-form-urlencoded',
  },
  body: {
    mode: 'urlencoded',
    urlencoded : [
      { key: 'title', value: 'Apple Magic Mouse'},
    ]
  }
};

pm.test("Test-01: User successfully update Product", function () {
    pm.sendRequest(postResponse, (error, response) => {
        pm.response.to.have.status(200);
        console.log(error ? error : response.json());
        });
});
```

**<u>Script 02:</u>**

```
//Failed to Update Product
const updateProductFailResponse = {
  url: 'https://dummyjson.com/products/two',
  method: 'PUT',
  header: {
    'Accept': '*/*',
    'Content-Type': 'application/x-www-form-urlencoded',
  },
  body: {
    mode: 'urlencoded',
    urlencoded : [
      { key: 'title', value: 'Apple Magic Mouse'},
    ]
  }
};

pm.test("Test-02: User Failed update Product", function () {
    pm.sendRequest(updateProductFailResponse, (error, response) => {
        pm.expect(response).to.have.property('code', 404);
        console.log(error ? error : response);
        });
});

```



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2f9ooeav7ilul5kc7wre.png)



For DELETE API -> Check 200 response and 404 response

**<u>Script 01:</u>**

```
//Successfully delete Product
const postResponse = {
  url: 'https://dummyjson.com/products/two',
  method: 'DELETE',
  header: {
    'Accept': '*/*',
    'Content-Type': 'application/x-www-form-urlencoded',
  }
};

pm.test("Test-01: User successfully Delete Product", function () {
    pm.sendRequest(postResponse, (error, response) => {
        pm.response.to.have.status(200);
        console.log(error ? error : response.json());
        });
});
```

**<u>Script 02:</u>**

```
//Failed delete Product
const deleteProductFailResponse = {
  url: 'https://dummyjson.com/products/90909',
  method: 'DELETE',
  header: {
    'Accept': '*/*',
    'Content-Type': 'application/x-www-form-urlencoded',
  }
};

pm.test("Test-02: User failed to Delete Product", function () {
    pm.sendRequest(deleteProductFailResponse, (error, response) => {
        pm.expect(response).to.have.property('code', 404);
        console.log(error ? error : response);
        });
});
```



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qk2lgf3nph6ptu0fwr92.png)




I mention some basic test scripts. To follow this script we can check any test scenarios without changing or run the API multiple request.

For more Script can follow this Postman Documentations
1. https://learning.postman.com/docs/writing-scripts/script-references/postman-sandbox-api-reference/
2. https://learning.postman.com/docs/writing-scripts/script-references/test-examples/#asserting-a-value-type
3. https://community.postman.com/t/skip-request-based-on-condition-collection/17976/4

**<u>Step 8:</u>** Now our both manual testing and scripting is done so its time to run our test case in local machine and generate report. First run the collection on Postman. Click on Runner and drag and drop the API collection Run the collection.

<u>Step - 1</u>
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mjmdbphiowhkndmmmo36.png)
                  
<u>Step - 2</u>
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rmzq5fo60sxd8l8udfyt.png)
                  

<u>Step - 3</u>
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gw7oxlbcgeks7fi9t5op.png)
                  

<u>Step - 4</u>
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dzcfpkpqm5v3yasqq7is.png)
                 
Now we run the postman collection using CLI. The most important tool when try to automated a collection run is Newman and Newman is a CLI tool that can take a postman collection run all the test and at the end generate the report. If we use Newman we can run a postman collection with API tests on any professional server that deals with building nd testing software, like for example - Jenkins. For that we have to install [newman](https://www.npmjs.com/package/newman). In order to use Newman locally on computer need to have **<u>nodejs</u>** install. If you already have newman then just check the version. Or if you do not have the newman then install it. For install newman follow the documentation - https://www.npmjs.com/package/newman

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q2mvp1mlb0263ntpmbt8.png)

```
newman --version
```
Run postman collection in cli we need to copy API collection JSON link
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1hylskms01t3p5lm3t83.png)
Then run the command

```
newman run https://www.getpostman.com/collections/da7c81fa859beeaf3d64
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uqdtdozbio91baxac3mm.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0ntq11i6hnfrcbvwzuy6.png)

Now you can Notice that the entire execuion has been successful. All the test have been generated properly.   

**<u>STEP - 09: HTML REPORT WITH NEWMAN</u>**
When working with newman is the possibility of generating reports and one of the report everyone use in the postman is [htmlextra](https://www.npmjs.com/package/newman-reporter-htmlextra) to generate a HTML report. This report will contain all log, full request, and full response. To install it simple go https://www.npmjs.com/package/newman-reporter-htmlextra and follow the installation step. 
To create a report run this command 

```
newman run https://www.getpostman.com/collections/da7c81fa859beeaf3d64 --reporters cli,htmlextra
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c6zx6imybv1syyrcncg3.png)


And here is my report. For mac the report was generated in file:///Users/your_user_name/newman/ -> folder. Can check request information in request section, Can investigate what happened with each request. Also have Failed test and Skip test section.

For More follow the tutorial - https://www.youtube.com/watch?v=VywxIQ2ZXw4

**<u>STEP - 10: Postman Collection in Jenkins</u>**
I integrate the test system with Jenkins so for that we need to install Jenkins. To install Jenkins we need Homebrew. Run this command to ensure that you have brew in your local machine.

```
brew --version
Homebrew 3.6.6
Homebrew/homebrew-core (git revision 2ce0c43d33a; last commit 2022-10-23)
Homebrew/homebrew-cask (git revision 38d1bb4d21; last commit 2022-10-23)
```
Install Jenkins run this command 
`brew install jenkins-lts`
After successfully install Jenkins, Lets start Jenkins to run command

```
brew services start jenkins-lts
```

To Unlock Jenkins and generate Administrator password, just copy the file and run command

```
cat /Users/appnapws54/.jenkins/secrets/initialAdminPassword
```
Copy the password and paste it.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4d10uk47kqr4fmcm2145.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oj22s6968bz7m9nw4o52.png)

For Jenkins Installation and Setup follow this Documentation and Video
1. https://www.youtube.com/watch?v=ANd6Qzkwjus
2. https://www.jenkins.io/download/lts/macos/

Set up Jenkins
1. With Jenkins running, go to http://localhost:8080 and sign in.

2. On the Dashboard page, select New Item on the left sidebar to create a new job.

3. Select a Freestyle project from the options. Name your project, and select OK.

4. In General > Build, add a build step in the project, and choose Execute Shell. The build step executes a shell command. Enter a shell command to run, such as newman run ~/Desktop/jenkins_demo_postman_collection.json.

5. In Build Environment > Build Environment, select Provide Node & npm bin/ folder to PATH and choose the NodeJS install you configured with Newman.

6. Select Save to finish creating the project.

Troubleshooting
7. Run this build test manually by selecting Build Now in the sidebar.

8. run build

Jenkins indicates that the build has failed with a red cross next to the build in the build history. This is because of the intentionally failed tests in the collection.

Select the build in the history list, then select Console Output to inspect what Newman returned.

Fix these tests inside your collection. Export it and then run the build again.

Jenkins indicates that the build succeeded with a green checkmark.

**Configure frequency of runs
To set the frequency with which Jenkins runs Newman:**

1. Open the build window.

2. Select Configure.

3. Go to Build Triggers and select Build periodically.

4. Enter a schedule. The syntax for setting the frequency to every 30 minutes is H/(30) * * * *.

5. Select the help icon next to Schedule to learn how to specify the build frequency.

6. Select Save.

Jenkins will now run Newman at your desired frequency and will tell you if the build failed or succeeded.

**Postman Integrating with Jenkins**
1. https://learning.postman.com/docs/running-collections/using-newman-cli/integration-with-jenkins/


**Jenkins Report generate and collect with github **
1.https://www.youtube.com/watch?v=3_SCjA9616c
2.https://blog.logrocket.com/how-automate-api-tests-postman/
https://www.youtube.com/watch?v=tKZsjZ0bGlU