Basic API Request Methods


GET - Use GET requests to retrieve resource representation/information only – and not to modify it in any way.

POST - Use POST APIs to create new subordinate resources, e.g., a file is subordinate to a directory containing it or a row is subordinate to a database table.

PUT - Use PUT APIs primarily to update existing resource (if the resource does not exist, then API may decide to create a new resource or not).

DELETE - As the name applies, DELETE APIs are used to delete resources (identified by the Request-URI).

REST API

REST stands for representational state transfer. It is a set of rules that developers follow when they create their API. An API is an application programming interface. It is essentially a set of functions and procedures allowing the creation of new applications that access the features or data of an operating system, application, or other service.

REST Assured is used to test and validate RESTful APIs in Java. See more info here.

When testing a REST API, the tests should generally focus on:

  • The HTTP Response Code
  • Other HTTP Headers in the response
  • The payload(JSON, XML)
Each test should only focus on one responsibility and include only one assertion.


A Simple Test

Here is an example of a simple test in Java.

@Test
public void givenUserDoesNotExists_whenUserInfoIsRetrieved_then404IsReceived()
throws ClientProtocolException, IOException {

 // Given

String name = RandomStringUtils.randomAlphabetic( 8 );
 HttpUriRequest request = new HttpGet ( "https://api.github.com/users/" + name );

 // When

HttpResponse httpResponse = HttpClientBuilder.create().build().execute( request );

// Then

assertThat(
httpResponse.getStatusLine().getStatusCode(),
equalTo(HttpStatus.SC_NOT_FOUND));
}


 

See how the test uses Given/When/Then syntax? This is a way to structure test cases, that is also sometimes known as Gherkin syntax. See here for more info on some good Gherkin guidelines.

This test above tests the HTTP status code of the request.

Parameters in REST Assured


Let's take a look at parameters that are used in RESTful APIs. There are two types of parameters.

The first one is the path parameter, where the parameter value is simply part of the URL that you call when you invoke the API. For example:

http://api.zippopotam.us/us/11211

http://api.zippopotam.us/ca/B2R

The country code "US, CA' as well as the following zip code are path parameters.

There are also query parameters, which we can recognize by the question mark (?) followed by key/value tuples separated by an equal sign.

For example:

http://md5.jsontest.com?text=chocolate

http://md5.jsontest.com?text=fish

The part after the question mark ("text") is the key and the part after the equals sign is the value. (Either "chocolate" or "fish" in this case.)

Sample Test

So now let's create a sample test in Eclipse.

1. Create a new Maven project. (See here if Maven isn't installed on your machine.)

2. Open your POM.xml file.

3. Add the following dependency to your POM.xml file:

<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured-all</artifactId>
<version>4.2.0</version>
<scope>test</scope>
</dependency>

So now let's try to create a new test.

4. Copy and paste the code below into your IDE in the src/test file.

import io.restassured.http.ContentType;
import org.junit.Test;

import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class Chapter2Test {

    @Test
    public void requestUsZipCode06824_checkStatusCode_expectHttp200() {

        given().
        when().
            get("http://zippopotam.us/us/06824").
        then().
            assertThat().
            statusCode(200);
    }
}




5. Run the code, and the test should pass, as 200 is the optimal API response.

6. Note that if we change the status code in the "Then" part of the test to 201, the test would then fail, as we aren't receiving the status code 201 back from the response.

7. We also might want to log a request. We can do this through the .log command. Here is an example:

@Test
    public void requestUsZipCode06824_logRequestAndResponseDetails() {
        given().
            log().all().
        when().
            get("http://zippopotam.us/us/06824").
        then().
            log().body();
    }


This will then output something that looks like this:


{

    "post code": "06824",

    "country": "United States",

    "country abbreviation": "US",

    "places": [

         {

            "place name": "Fairfield",

      
            $ "longitude": "-73.2681",

      
            $ "state": "Connecticut",

            "state abbreviation": "CT",

      
            $ "latitude": "41.1692"

   }


   ]

}

This is what is known as the payload, which is either in JSON or XML. In this case, it is in JSON.

You can try this out on your own by adding the Java code (NOT the JSON payload) to your src/test file under the first test where we tested for the 200 status code.

-- BenRosner - 25 Jun 2020
Topic revision: r6 - 30 Jun 2020, BenRosner
© 2020 Ultranauts - 75 Broad Street, 2nd Floor, Suite 206, New York, NY 10004 - info@ultranauts.co