Javascript: Automate REST API using AXIOS

While working with test automation we need API tests to be run as part of the automation.
Those who are familiar with Java, they mostly use Rest Assured library to automate REST apis.
But for javascript Rest assured is not supported and hence we have many javascript libraries who does the job for us. Among many such libraries I have tried few of them and they pretty much work similar.

Here are few of the liraries:
1- Axios
https://www.npmjs.com/package/axios
2- Supertest
https://www.npmjs.com/package/supertest
3- request (http) Do not user – Deprecated
https://github.com/request/request/issues/3143

I found AXIOS to be better and easy to write tests, but again superTest is also good one.
I will explain how to use AXIOS in this article and also focus on Async calls which is importat while we inject API calls in between UI calls (Protractor)

Setup:
1- Install npm
2- Install axios
npm install –save-dev axios

3- Create a test file name : testApi.js

//This is to enable axios autosuggestion and make axios command availabe
var axios = require("axios").default;

var baseUrl = 'https://reqres.in/api/users/2';
describe("First Test Suite", function () {

it("API Test using AXIOS", async () => {
         //It waits till API response is received then moves to print the 
         //  response
        const response = await axios.get(baseUrl); 
         // response object has data property which stored the json response 
        //body
        console.log('Response=' + JSON.stringify(response.data))
    })
}

If you observe we have used async and await in the api.
The reason is, in javascript we must follow async / sync to let it know that we are expecting delay or wait till we get the response or call back is finished.
Else it will move to next line without having the api call finished.
It does not work like java, the line by line execution as long as we mention async .

If we remove async and await in the above code, we will get undefined response.

So it is important to use async and await while using API calls even in Protractor UI code.

4- Printing json response to console

// response object has data property which stored the json response body
console.log('Response=' + JSON.stringify(response.data))

5- Parsing string to json

//Json response is converted to string
var jsonResToString=JSON.stringify(response.data);

//Converting it back to json object
var myObj = JSON.parse(jsonResToString)

//Printing it to console
var jsonResToString=JSON.stringify(myObj.data);

6- Extracting value from json object

var myObj = JSON.parse(jsonResToString)

//Printing it to console
var jsonResToString=JSON.stringify(myObj.data);

//Extracting value (instead of jsonKey pass the key of json
var value = myObj.jsonKey

Leave a Reply