Rest Assured #9 - Automating POST Request (User Registration API)
In this article, I have covered how to automate POST requests in Rest Assured with an example of user registration API.
API Details
Endpoint - https://test-api.k6.io/user/register/
HTTP Method Allowed - POST, OPTIONS
Header - Content-Type: application/json
Request Body Schema
{
"name": "User Create Api",
"description": "",
"renders": [
"application/json",
"text/html"
],
"parses": [
"application/json",
"application/x-www-form-urlencoded",
"multipart/form-data"
],
"actions": {
"POST": {
"username": {
"type": "string",
"required": true,
"read_only": false,
"label": "Username",
"help_text": "Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.",
"max_length": 150
},
"first_name": {
"type": "string",
"required": false,
"read_only": false,
"label": "First name",
"max_length": 150
},
"last_name": {
"type": "string",
"required": false,
"read_only": false,
"label": "Last name",
"max_length": 150
},
"email": {
"type": "email",
"required": false,
"read_only": false,
"label": "Email address",
"max_length": 254
},
"password": {
"type": "string",
"required": true,
"read_only": false,
"label": "Password"
}
}
}
}
User Registration only with Mandatory Field Test case
Test Case ID: UR001
Test Case Summary: User Registration API - Only Mandatory Field - unique username and password field
Test Objective: Verify that the user registration API creates a new user account with a mandatory fields - username and password and returns a successful response.
Test Steps:
Prepare the test data
- Create a test user with a valid username and password.
Send a POST request to the user registration API with the test data as the request body
Verify that the API returns a successful response with a 201 HTTP status code.
Verify that the response contains a unique identifier for the new username.
Test Data:
HTTP Method - POST
Endpoint - https://test-api.k6.io/user/register/
Header - Content-Type: application/json
Request Payload - username should be unique
{
"username": "TestUser2023020720401212",
"password": "1"
}
Expected Results:
The response should have: Status Code - 201
Response Body - It should contain the user's name we have passed in the request body
{
"username": "TestUser2023020720401212",
"first_name": "",
"last_name": "",
"email": ""
}
Testing with Postman
Before automating this test case we will first test using Postman as shown below
Setup RestAssured using Maven
To start with Rest Assured for API testing we need first to import the Rest Assured package, we will need to add the RestAssured dependency to your project's pom.xml file in the Maven project. Here is an example of how to do this:
Rest Assured Maven Dependency Link - https://mvnrepository.com/artifact/io.rest-assured/rest-assured
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.3.0</version>
</dependency>
If you use the scope as a test for the RestAssured package, then RestAssured can be only imported under the src/test directory. As I am going to write API-related code into the src/main directory and test under the test directory I have removed the test scope in the above pom declaration.
I will add TestNG dependency to use test-related annotations so added it below in the pom file
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.7.1</version>
<scope>test</scope>
</dependency>
Automate POST request with Rest Assured
To automate user registration API we will create two classes in the maven project
UserRegistration - To send post request for user registration
UserRegistrationTest - To test user registration api
UserRegistration Class
- Declare instance variable to set baseUri, service path, request body and response
private String baseUri = "https://test-api.k6.io";
private String userRegisterPath = "/user/register/";
private String userRegistrationRequestBody;
private Response response;
- Create a constructor to set the request body and Rest Assured that base URI
public UserRegistration(String userName, String password){
RestAssured.baseURI = baseUri;
userRegistrationRequestBody = "{\"username\": \""+userName+"\",\"password\": \""+password+"\"}";
}
- Send a post request to createUser
public void createUser(){
response = RestAssured.given()
.contentType(ContentType.JSON)
.body(userRegistrationRequestBody)
.post(userRegisterPath);
}
RestAssured.given(): This method returns an instance of RequestSpecification.
contentType(ContentType.JSON): This method returns the same RequestSpecification instance on which it was called, allowing for method chaining.
body(userRegistrationRequestBody): This method returns the same RequestSpecification instance on which it was called, allowing for method chaining.
post(userRegisterPath): This method returns an instance of Response, which represents the response to the API request.
- Write methods to extract the response status code and value from the response body
public int getStatusCode(){
return response.getStatusCode();
}
public String getResponseBodyUsingKey(String key){
JsonPath jsonPath = response.jsonPath();
return jsonPath.getString(key);
}
The "JSON path" object is created from the "response" object and used to extract the value of the specified key from the response body.
Below are complete code defined under src/main directory
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
public class UserRegistration {
private String baseUri = "https://test-api.k6.io";
private String userRegisterPath = "/user/register/";
private String userRegistrationRequestBody;
private Response response;
public UserRegistration(String userName, String password){
RestAssured.baseURI = baseUri;
userRegistrationRequestBody = "{\"username\": \""+userName+"\",\"password\": \""+password+"\"}";
}
public void createUser(){
response = RestAssured.given()
.contentType(ContentType.JSON)
.body(userRegistrationRequestBody)
.post(userRegisterPath);
}
public int getStatusCode(){
return response.getStatusCode();
}
public String getResponseBodyUsingKey(String key){
JsonPath jsonPath = response.jsonPath();
return jsonPath.getString(key);
}
}
UserRegistrationTest Class
Finally, we will write a test method to test the user registration API under test directory
Create userName variable with a random string
Call UserRegistration class to perform post request and validate response code and response body
import org.testng.Assert;
import org.testng.annotations.Test;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
public class UserRegistrationTest {
@Test
public void CreatingRequestTest(){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String dateTime = dateFormat.format(new Date());
Random random = new Random();
int fourDigitRandom = 1000 + random.nextInt(9000);
String userName = "TestUser"+dateTime+fourDigitRandom;
String password = "1";
UserRegistration userRegistration = new UserRegistration(userName,password);
userRegistration.createUser();
Assert.assertEquals(userRegistration.getStatusCode(),201);
Assert.assertEquals(userRegistration.getResponseBodyUsingKey("username"),username);
}
}
GitHub Url - https://github.com/sksingh329/RestAssuredTutorials