# Assertions for API Test scripts

**URL:** <https://community.postman.com/t/assertions-for-api-test-scripts/8717>\
**Category:** Help Hub\
**Tags:** tests, responseassertion, array, postman-api\
**Created:** [October 31, 2019, 9:11am UTC](https://community.postman.com/t/assertions-for-api-test-scripts/8717 "2019-10-31T09:11:14Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![gayaniw](https://avatars.discourse-cdn.com/v4/letter/g/5fc32e/32.png) [@gayaniw](https://community.postman.com/u/gayaniw)\
**Post date:** [October 31, 2019, 9:11am UTC](https://community.postman.com/t/assertions-for-api-test-scripts/8717/1 "2019-10-31T09:11:14Z")

</div>

**API Assertions**

API testing is all about assertions. There are two steps to write assertions

- Parse the response body
- Write the test

Response body may come as a JSON, XML,HTML, Plain text or CSV. But the common format would be the JSON. In postman to parse the response body there’s a builtin library “pm”

pm.response.json() will do the job!

Here are the few common assertions that might need to verify API responses.

1. Verify the status code

1. Suppose you are getting below API response and you need to verify the each value returned in the JSON object. \> {

> ```
> "id": "15003",
> "namespace": "se.cambio.featuretoggle.demo",
> "name": "demo-feature-one",
> "enabled": false,
> "description": "demo feature one display Description",
> "status": "ACTIVE",
> "type": "INTERNAL",
> "displayName": "demo feature one display name"
> },
> {
> "id": "15010",
> "namespace": "se.cambio.featuretoggle.as",
> "name": "as-feature-three",
> "enabled": true,
> "description": "Description of feature three",
> "status": "ACTIVE",
> "type": "INTERNAL",
> "displayName": "AS Feature three"
> },
> 
> ```

> `let jsonData = pm.response.json();`  
> `let ReleaseObject;`

//Have a for loop to traverse through till you get the object with the name as in the if condition.

> ```
> for (let Data of jsonData) {
> console.log(Data);
> if (Data.name == "demo-feature-one") {
> ReleaseObject = Data;
> }
> 
> ```
> 
> }
> 
> ```
> pm.test("Verify feature is release ready", function() {
> pm.expect(ReleaseObject.id).to.not.be.null;  
> pm.expect(ReleaseObject.namespace).to.equal("se.cambio.featuretoggle.demo");
> pm.expect(ReleaseObject.enabled).to.be.false;
> pm.expect(ReleaseObject.status).to.eql("ACTIVE");
> pm.expect(ReleaseObject.togglestatus).to.eql("Enabled");
> 
> ```
> 
> });

1. Suppose you need to see all the JSON objects returned in the API response are equal to some condition. In case if you want to assert that all the results are in active status.

2. You may need to verify no of records in the DB is matched with the results count returned by the API.

> `const items = pm.response.json();`  
> `var a = (items && items.length) || 0;`  
> `console.log(a);`  
> `pm.test("Verify Release ready item count", function() {`  
> `pm.expect(a).to.equal(30, ‘Count must equal to 30’);`  
> `});`

1. Verify returned array is empty

> ```
> pm.test("Verify no results found", function(){ 
> pm.expect([]).to.be.empty;
> });
> 
> ```

1. Verify array includes an element that you search

> ```
> pm.test("Verify search element found in the array", function(){
> pm.expect([1,2,3]).to.include(3);`
> });
> 
> ```

1. **Assertions of an array element**

URL [http://www.mocky.io/v2/5dba8cec300000b000028f82](http://www.mocky.io/v2/5dba8cec300000b000028f82)

Assertion Verify the order status of order id =3

```
JSON Response	{
    "companyid": 1000,
    "region": "APAC",
    "orderList": [
        {
            "id": 100,
            "orderName": "Order1",
            "validOrder": true
        },
        {
            "id": 200,
            "orderName": "Order2",
            "validOrder": false
        },
        {
            "id": 300,
            "orderName": "Order3",
            "validOrder": true
        }
    ]
}

```

The best approach is to traverse all the objects in the response to see the order with order id 3. This would be the optimum solution when we don’t know the array index of the object we want to see.

```
                let jsonData = pm.response.json();
                    let Order;
                    for(let filter of jsonData.orderList){
                     //console.log(filter);
            
        if(filter.orderName == "Order3"){
            Order=filter;
            console.log(Order);
        }
    }
        pm.test("verify the order status", function(){
            pm.expect(Order.orderName).to.eql("Order3"),
            pm.expect(Order.validOrder).to.be.true;
        });

```

**8. Assertions on nested objects**  
URL [http://www.mocky.io/v2/5dba84213000008700028f37](http://www.mocky.io/v2/5dba84213000008700028f37)

See the JSON response below. Our target is to verify the display status of the avator.

Response Body:

```
 {
     "id": 9,
     "email": "tobias.funke@reqres.in",
     "first_name": "Tobias",
     "last_name": "Funke",
     "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/vivekprvr/128.jpg",
     "rev": {
         "revid": 12334,
         "bookmarkstatus": "true",
         "noofbookmarks": 3,
         "comments": {
             "status": "active",
             "commentid": 123
         }
     },
     "limits": {
         "289283020299020202": {
             "avator": {
                 "avatorname": "zombie",
                 "count": 1,
                 "displaystatus": "yes"
             }
         }
     }
}

```

_Assertion This test is to verify Avator Display status_

```
 let jsonData = pm.response.json();
 //To identify the structre of the array return the jsonData result to console as below
console.log(jsonData); // check the postman console, to see the value passed to the variable jsonData.

 // you will see the array structure. as this is an object navigate to the the required property you want to verify using dot operator as below.
  console.log(jsonData.rev.comments.status);

 // Assign the status to a variable and verify if it is active
   let commentStatus = jsonData.rev.comments.status;
   pm.test("Verify comments status", function(){
   pm.expect(commentStatus).to.eql("active");
     });
     
    //This test is to verify Avator Display status
     let AvatorStatus;
      for(let key in jsonData.limits){
          console.log(jsonData.limits[key]);
          console.log(jsonData.limits[key].hasOwnProperty("avator"));
          if(jsonData.limits[key].hasOwnProperty('avator')){
            AvatorStatus = jsonData.limits[key].avator.displaystatus;
      }
     }
    pm.test("display status is true", function(){
      pm.expect(AvatorStatus).to.eql("yes");
      });

```

---

<div class="post-metadata">

**Author:** ![orbital-module-pilo1](https://avatars.discourse-cdn.com/v4/letter/o/958977/32.png) [@orbital-module-pilo1](https://community.postman.com/u/orbital-module-pilo1)\
**Post date:** [July 22, 2021, 6:25pm UTC](https://community.postman.com/t/assertions-for-api-test-scripts/8717/2 "2021-07-22T18:25:54Z")

</div>

Hi ,  
Please help in Delete Assert  
json =

```auto
[
  {
    "InterfaceGroupId": "60f9ae30b03eb7c5d8734cc9",
    "GroupName": "madhu5zb8lv6dokgroup",
    "Description": "from MOB",
    "TenantCsn": "madhucsn",
    "IsDefault": false,
    "IsDeleted": false,
    "CreationDate": null
  },
  {
    "InterfaceGroupId": "60f92584b03eb7c5d8734cc8",
    "GroupName": "madhuom4s4vokqxgroup",
    "Description": "from MOB",
    "TenantCsn": "madhucsn",
    "IsDefault": false,
    "IsDeleted": false,
    "CreationDate": null
  }
]

```

1.ENV variable GroupName exists in postman  
2.Delete API is looking for “InterfaceGroupId” in the request Body  
3.I want to pass that InterfaceGroupId which is in ENV variable “GroupName”

---

<div class="post-metadata">

**Author:** ![system](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/system/32/29796_2.png) [@system](https://community.postman.com/u/system)\
**Post date:** [December 12, 2024, 2:46pm UTC](https://community.postman.com/t/assertions-for-api-test-scripts/8717/3 "2024-12-12T14:46:54Z")

</div>

Closed on December 12, 2024, 2:46pm UTC

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.
