In this REST Assured tutorial, I will demonstrate how to evaluate the JSON content that is returned in the response body of an HTTP response.
What is REST Assured?
REST Assured is a Java-based library for testing RESTful web services. It provides a domain-specific language (DSL) for writing tests that interact with web services using HTTP requests and responses. REST Assured is built on top of the popular testing framework, JUnit, and provides several features that make it easy to write and execute tests for RESTful APIs.
REST Assured allows you to easily create HTTP requests and inspect the responses. You can use REST Assured to send requests using HTTP methods such as GET, POST, PUT, DELETE, and more. REST Assured also provides several ways to validate the response, such as checking the response code, headers, and the content of the response body.
REST Assured supports multiple serialization formats, including JSON, XML, and others. It allows you to easily parse the response and extract specific data elements that you want to test. REST Assured also supports authentication and cookies, making it easy to test web services that require authentication.
Overall, REST Assured is a powerful and flexible library that makes it easy to test RESTful web services. Its intuitive DSL and integration with JUnit make it an excellent choice for developers and testers who want to create robust and reliable tests for their APIs.
JSON Response to validate
Let’s assume that we have a RESTful web service endpoint that returns user details with the following structure:
{ "userId": "Y3vWa8QwjK0DW6NmvB4HsXIV9gHg1q", "firstName": "Sergey", "lastName": "Kargopolov", "email": "[email protected]" }
API Endpoint
To obtain the JSON representation of user details mentioned above, we need to send an HTTP GET request to the following URL:
Request URL:
http://localhost:8888/users/Y3vWa8QwjK0DW6NmvB4HsXIV9gHg1q
Since we might be using Spring Security, I will include the Authorization Header that contains the JSON Web Token:
Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ0ZXN0QHRlc3QuY29tIiwiZXhwIjoxNTI5NDIwMjQzfQ.qepmpAizfH9QHNygKM-7fhhkpvJSYMUOQOTKemLeYCcy2E1yrFNxA61YCqio7rWGUmSz3KE2osqlo-7LhWzRTQ
REST Assured Test Method
Below is a working example of a test method that performs the following actions:
- Sends an HTTP GET request to the RESTful web service endpoint URL mentioned above and includes the Authorization Header in the HTTP request.
- Validates the HTTP response body to check if it contains a specific string value.
- Validates the JSON content to check if it contains a specific JSON key and value.
NOTE: To validate the JSON content, we will use the JsonPath
class, which is located in the io.restassured.path.json
package.
Setting the Request Base URI
RestAssured.baseURI = "http://localhost:8888";
The above line of code sets the base URI for all the subsequent HTTP requests that will be made using REST Assured in the tutorial.
When we test APIs using REST Assured, we need to specify the base URI for the API endpoint that we want to test. The base URI is the common part of the API endpoint’s URL that remains the same for all the requests that we will make.
In this case, the base URI is set to “http://localhost:8888“, which means that all the requests made using REST Assured in the tutorial will be sent to an API endpoint hosted on the local machine on port 8888.
By setting the base URI, we don’t have to specify the full URL for each request. Instead, we can use relative URLs for each request, and REST Assured will automatically append them to the base URI to create the full URL for the request.
Prepare and Send HTTP GET Request with REST Assured
RequestSpecification httpRequest = RestAssured.given(); // Set HTTP Headers httpRequest.header("Content-Type", "application/json"); httpRequest.header("Authorization", "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ0ZXN0QHRlc3QuY29tIiwiZXhwIjoxNTI5NDIwMjQzfQ.qepmpAizfH9QHNygKM-7fhhkpvJSYMUOQOTKemLeYCcy2E1yrFNxA61YCqio7rWGUmSz3KE2osqlo-7LhWzRTQ"); Response response = httpRequest.get("/users/Y3vWa8QwjK0DW6NmvB4HsXIV9gHg1q");
The first line of code, RequestSpecification httpRequest = RestAssured.given();
, creates a new HTTP request specification using the “given” method of the RestAssured class. An HTTP request specification is a collection of various parameters that we can set to configure the HTTP request that we want to send.
The second and third lines of code, httpRequest.header("Content-Type", "application/json");
and httpRequest.header("Authorization", "Bearer...");
, set two HTTP headers in the request specification. HTTP headers are additional pieces of information that we can send with an HTTP request to provide more context to the server about the request.
The fourth line of code, Response response = httpRequest.get("/users/Y3vWa8QwjK0DW6NmvB4HsXIV9gHg1q");
, sends an HTTP GET request to the API endpoint with the relative URL “/users/Y3vWa8QwjK0DW6NmvB4HsXIV9gHg1q“. The request specification created in the previous lines of code is used to set the HTTP headers for the request. The response returned by the API endpoint is stored in a variable called “response”.
By using a request specification, we can set various parameters like headers, request body, query parameters, etc., for our HTTP request, which gives us more control over the request and helps us to test different scenarios for our API.
Get Response Body with REST Assured
// Get Response Body ResponseBody body = response.getBody();
The above line of code is used in REST Assured to read the response body from an HTTP response object.
When we send a request to an API endpoint, the server responds with an HTTP response object, which contains various information such as the response code, headers, and response body. The response body is the data returned by the API in response to our request.
In this line of code, we are getting the response body from the HTTP response object and storing it in a variable called “body”. We can then use this variable to perform further assertions on the response body to verify that the API is returning the expected data.
GET Response Body As String
// Get Response Body as String String bodyStringValue = body.asString();
This line of code converts the response body from the “body” variable into a string value and stores it in a variable called “bodyStringValue”. This is done because most of the assertions in REST Assured expect a string value as input.
Validate if the Response Body Contains a Specific String
// Validate if Response Body Contains a specific String Assert.assertTrue(bodyStringValue.contains("firstName"));
This line of code performs an assertion on the response body to check if it contains the string “firstName”. The assertion checks if the value of “bodyStringValue” contains the string “firstName” and returns true if it does. If the assertion fails, it will throw an AssertionError. This assertion is useful in verifying that the API is returning the expected data and can be used to ensure that the response body contains specific information.
Validate Specific JSON Element
// Get JSON Representation from Response Body JsonPath jsonPathEvaluator = response.jsonPath(); // Get specific element from JSON document String firstName = jsonPathEvaluator.get("firstName"); // Validate if the specific JSON element is equal to expected value Assert.assertTrue(firstName.equalsIgnoreCase("Sergey"));
The first line of code, JsonPath jsonPathEvaluator = response.jsonPath();
, creates a JsonPath object from the response object using REST Assured. A JsonPath object is used to parse and extract data from JSON (JavaScript Object Notation) responses. We can use this object to navigate through the response body and extract specific values.
The second line of code, String firstName = jsonPathEvaluator.get("firstName");
, extracts the value of the “firstName” key from the JSON response using the “get” method of the JsonPath object. The value is stored in a variable called “firstName“.
The third line of code, Assert.assertTrue(firstName.equalsIgnoreCase("Sergey"));
, performs an assertion on the value of “firstName“. The assertion checks if the value of “firstName” is equal to the string “Sergey” (ignoring case), and returns true if it does. If the assertion fails, it will throw an AssertionError. This assertion is useful in verifying that the API is returning the expected data and can be used to ensure that the response body contains specific information.
REST Assured Test Method Complete Code Example
@Test public void validateResponseJSONBody_test() { RestAssured.baseURI = "http://localhost:8888"; RequestSpecification httpRequest = RestAssured.given(); // Set HTTP Headers httpRequest.header("Content-Type", "application/json"); httpRequest.header("Authorization", "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ0ZXN0QHRlc3QuY29tIiwiZXhwIjoxNTI5NDIwMjQzfQ.qepmpAizfH9QHNygKM-7fhhkpvJSYMUOQOTKemLeYCcy2E1yrFNxA61YCqio7rWGUmSz3KE2osqlo-7LhWzRTQ"); Response response = httpRequest.get("/users/Y3vWa8QwjK0DW6NmvB4HsXIV9gHg1q"); // Get Response Body ResponseBody body = response.getBody(); // Get Response Body as String String bodyStringValue = body.asString(); // Validate if Response Body Contains a specific String Assert.assertTrue(bodyStringValue.contains("firstName")); // Get JSON Representation from Response Body JsonPath jsonPathEvaluator = response.jsonPath(); // Get specific element from JSON document String firstName = jsonPathEvaluator.get("firstName"); // Validate if the specific JSON element is equal to expected value Assert.assertTrue(firstName.equalsIgnoreCase("Sergey")); }
Conclusion
In conclusion, REST Assured is a powerful framework for validating JSON responses in RESTful APIs. By leveraging REST Assured, developers can easily verify the correctness and structure of JSON data returned by API endpoints. With the ability to set up the API endpoint, retrieve the response body, and validate specific elements, REST Assured provides an efficient and effective solution for testing and validating JSON responses.
By following the techniques outlined in this tutorial, developers can confidently ensure the integrity and correctness of their API’s JSON responses. Are you passionate about testing RESTful web services? Dive into our in-depth tutorial available on the Testing Java Code page, where we explore the powerful features of REST Assured. Learn how to write elegant tests, extract meaningful data, and validate the behavior of your RESTful APIs.
Happy learning!
hi could you please upload how to validate all json payload