API Testing - Java and JavaScript Libraries

Introduction

In this blog, I have discussed the difference in performing API Automation Testing using Java and javascript programming languages.

For Java, I have used rest assured library for API Testing.

And for Javascript, I have used supertest library for API Testing.

Style of writing

Rest Assured

// Specify the base URL to the RESTful web service 
RestAssured.baseURI = "https://demoqa.com/BookStore/v1/Books"; 
// Get the RequestSpecification of the request to be sent to the server. 
RequestSpecification httpRequest = RestAssured.given(); 
// specify the method type (GET) and the parameters if any. 
//In this case the request does not take any parameters 
Response response = httpRequest.request(Method.GET, "");
// Print the status and message body of the response received from the server 
System.out.println("Status received => " + response.getStatusLine()); 
System.out.println("Response=>" + response.prettyPrint()); 

SuperTest

Once the request body and headers are set we need to call the end function which performs the request and invokes fn(err, res). in which we can perform the assertions and in case if there is an error returned from the API request, it will throw an error. We need to call the done function once our test is complete. This is necessary as it informs the calling function(err,res)that the task is completed.

it('should successfully pass the test for get api without query param', (done) => {
       Request(basuri)
           .get('/api/users/2')
           .end(function (err, res) {
               expect(res.statusCode).to.be.equal(200);
               expect(res.body.data.id).to.be.equal(2);
               expect(res.body.data.first_name).to.be.equal('Janet');
               done();
           });
   });

Sending query param

Rest Assured

User queryparam method

QueryParam can be passed as:

String endpoint = "http://example.com/building"; 
var response = given()
.queryParam("globalDates", "{\"startMs\":1473672973818,\"endMs\":1481448973817,\"period\":90}")
.queryParam("startFrom", "0").queryParam("limitTo", "6").queryParam("loadTvData", true)
.queryParam("startFrom", "0").queryParam("userId", "5834fb36981baacb6a876427")
.when().get(endpoint).then();

SuperTest

const queryParams = {
  param1: 'value1',
  param2: 'value2'
};

request(app)
  .get('/endpoint')
  .query(queryParams)
  .expect(200)
  .end((err, res) => {
    if (err) throw err;

    // Handle the response
    console.log(res.body);
  });

Sending path param

Rest Assured

Use pathparam method

Response response = RestAssured.given()
                .pathParam("userId", userId)
                .get(endpoint);

SuperTest

const userId = '123456';
request(app)
  .get(`/users/${userId}/profile`)
  .expect(200)
  .end((err, res) => {
    if (err) throw err;

    // Handle the response
    console.log(res.body);
  });

Sending authentication type

Rest Assured

Response response = RestAssured.given()
                .auth()
                .basic("username", "password")
                .get("/endpoint");

 Response response = RestAssured.given()
                .auth()
                .oauth2("your_token_here")
                .get("/endpoint");

 RestAssured.baseURI = "https://api.example.com";

        // JWT token
        String jwtToken = "your_jwt_token_here";

        // Send a GET request with the JWT token
        Response response = RestAssured.given()
                .header("Authorization", "Bearer " + jwtToken)
                .get("/endpoint");

SuperTest

const token = 'your_token_here';

request(app)
  .get('/endpoint')
  .set('Authorization', `Bearer ${token}`)
  .expect(200)
  .end((err, res) => {
    if (err) throw err;

    // Handle the response
    console.log(res.body);
  });

Sending request headers

Rest Assured

Response response = RestAssured.given()
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer your_token_here")
                .get("/endpoint");

SuperTest

request(app)
  .get('/endpoint')
  .set('Content-Type', 'application/json')
  .set('Authorization', 'Bearer your_token_here')
  .expect(200)
  .end((err, res) => {
    if (err) throw err;

    // Handle the response
    console.log(res.body);
  });

Logging

Rest Assured

If we use log().all() after given then it will log all the request headers if we use log().all() after then section it will log all response

RestAssured.baseURI="https://reqres.in/"; 
    String requestBody = "{\n"                 + "    \"email\": \"[email protected]\",\n"                 + "    \"password\": \"cityslicka\"\n"                 + "}"; 

Response res=given().
contentType(ContentType.JSON).     
body(requestBody). 
when().         
post("api/login").     
    then().log().all()     
    .extract().     
    response();     
 Assert.assertEquals(200, res.statusCode());         
 }

SuperTest

debug(console.log)

In Supertest, you can log request headers by using the debug() method provided by Supertest

Ways of sending JSON body in post request

Rest Assured

We can send 

  1. Directly hardcoded in code
  2. Store JSON in another class file and refer in your code
  3. Create a pojo class use the serialization concept and convert the pojo class object to json object using objectmapper class which is available in jackson api dependency

SuperTest

const request = require('supertest');
const faker = require('faker');
const app = require('./app'); // Replace './app' with the path to your Express app

// Generate dynamic data using Faker
const requestBody = {
  name: faker.name.findName(),
  age: faker.random.number({ min: 18, max: 65 }),
  email: faker.internet.email()
};

// Send a POST request with the dynamic JSON body
request(app)
  .post('/endpoint')
  .send(requestBody)
  .expect(201)
  .end((err, res) => {
    if (err) throw err;

    // Handle the response
    console.log(res.body);
  });

Thank you, Happy learning.