Create a REST API test case

Create a REST API test case with Java script. Upload this script to Cloud App Management and run it on a schedule.

Create and schedule a Java script to test your REST APIs. Use Java script to:
  • Monitor your REST API in every stage of DevOps pipeline.
  • Automate detection of REST API defects in the continuous pipeline.
  • Test REST API transaction response time in the continuous pipeline.
  • Test REST API uptime and transaction business logic in production.

How to write a REST API test case with Java script

  1. Use describe to create a script step.
    Every request should be in a step.
    Every step should have only one request, use multiple steps if there are multiple requests.
    Steps run in sequence. Subsequent steps run after the previous step is finish and the complete call is reached.
    The syntax is as follows:
    describe(stepName, function(complete){}) complete
  2. To pass variables from the synthetic test configuration, use the following syntax $globalContext[VAR_NAME]
    For example,
    describe('step 1', function(complete){
    let datastr = {"name": $globalContext['name'],"job": $globalContext['job']};
    request.post("http://localhost:18080/api/users",
    {headers:{'Content-type': 'application/json'}, body: JSON.stringify(datastr)
    },
    function(error,response,body){
    assert.ok (response && response.statusCode == 200, "Response code is not 200");
    var bodyObj = JSON.parse(body);
    assert.ok(bodyObj['name'] == $globalContext['name'], "Pass parameter name failed");
    assert.ok(bodyObj['job'] == $globalContext['job'], "Pass parameter jobfailed");
    }
    );
    });
  3. To pass data to the next step or next N step use the following syntax: complete(DATA). Where DATA can be any type, for example, string, number or object. For example:
    complete(['value', 1234, 'value2']), complete({"key1":"value1","key2":"value2"})
    Pass data to next steps from step 1, for example:
    complete({"key1":"value1","key2":"value2"})
    Read data from previous step by using the following syntax: $stepContext['preStepResult'] For example, Read data "key1" in step 2 by
    var k = $stepContext['preStepResult']['key1']
    Read "key1" in step 3 by, for example:
    var k = $stepContext['key1']
    If you do not need to pass anything to the next step, use complete().
  4. To validate your results, call an assert method to validate the endpoint response. If the condition of the assert method are met, an alert notification is triggered.
    For example:
    assert.ok(response && response.statusCode == 200, "step failed ,error is " + error);
    Validate response content, for example:
    let bodyObj = typeof body == 'string': JSON.parse(body): body;
    assert.ok(bodyObj.id != null, "Resource create failed, not resource ID");
  5. Use the following syntax for a GET request:
    let baseUrl = 'https://reqres.in/api/messages';
    // Make GET request
    describe('get messages', function (complete) {
        request.get(baseUrl, {}, function (error, response) {
            // Validate the response code, if assertion fails, log "failed to get message " plus results as error message on synthetic dashboard
            assert.ok(response && response.statusCode == 200, "failed to get message" + error);
            complete();
        });
    });
  6. Use the following syntax for a POST form request:
    
    let baseUrl = 'http://localhost:3000';
    describe('post form content',function(complete){
    // Define endpoint URL
    let url = baseUrl + "/messages";
    // Define form content data
    let formData = {"text": "Hi Meg is here"};
    // Define headers such as "context-type"
    let header1 = {"contex-type": "application/json"};
    // Make POST request
    request.post(url, {header: header1, form: formData}, function(error, response) {
    // Validate the response code, if assertion fails, log "failed to create message, error is " plus results as error message on synthetic dashboard
    assert.ok(response && response.statusCode == 200, "failed to create message, error is " + error);
    complete();
    });
    });
    
  7. Use the following syntax for a POST JSON request:
    //Send Json content
    let baseUrl = 'https://reqres.in';
    describe('post json content', function (complete) {
        // Define endpoint URL
        let url = baseUrl + "/api/users";
        // Define JSON data
        let data = { "job": "leader","name": "morpheus" };
        // Define headers
        let header1 = { "contex-type": "application/json" };
        // Make POST request
        request.post(url, { header: header1, json: data }, function (error, response) {
            // Validate the response code, if assertion fails, log "failed to create message, error is " plus results as error message on synthetic dashboard
            assert.ok(response && response.statusCode == 201, "failed to create message, error is " + error);
            complete();
        });
    });
  8. Use the following syntax to send a TLS/SSL Protocol request with cert:
    describe('test TLS/SSL',function(complete){
    const cert= <client.crt string>
    , key= <client.key string>
    , ca= <ca.cert.pem string>;
    
    const options = {
    url: 'https://api.some-server.com/',
    cert: cert,
    key: key,
    passphrase: <password>,
    ca: ca
    };
    request.get(options, function(error, response, body){
    complete()
    });
    });
  9. Use the following syntax to send a basic authentication request:
    
    describe('step 1', function(complete){
    request.get('http://some.server.com/', {
    // Define authentication credentials
    'auth': {
    'user': 'username',
    'pass': 'password',
    'sendImmediately': false
    }
    });
    })
    
  10. Use the following syntax to send a bear authentication request. Set the bearer value in the auth parameter. The value can be either a string or a function returning a string.
    describe('step 1', function(complete){
    request.get('http://some.server.com/', {
    'auth': {
    'bearer': authToken
    }
    }
    })
  11. Use the following syntax to send a request with http proxy:
    
    describe('step 1', function(complete){
    request.get('http://www.ibm.com',{
    "proxy":  "http://PROXY_HOST:PROXY_PORT"
    }, function (error, response, body){
    //console.log(body);
    })
    })
  12. Optional: Server Name Indication(SNI) is supported from IBM® Cloud App Management V2019.3.0. You can add servername in the request to get the right SSL certificate from the specific server. Use the following syntax to send request to SNI enabled web server:
    describe('step 1',function(complete){
       request.get({
          url: 'https://some.server.name',
            servername: 'some.server.name'
      }, function(error, response, body){
          console.log(response.statusCode);
          complete();
       });
    });