DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Build a REST API With Just 2 Classes in Java and Quarkus
  • Get Some Rest! A Full API Stack
  • Cypress API Testing: A Detailed Guide
  • API Testing With Cypress

Trending

  • Overcoming React Development Hurdles: A Guide for Developers
  • Docker Model Runner: Streamlining AI Deployment for Developers
  • Evolution of Cloud Services for MCP/A2A Protocols in AI Agents
  • Unlocking AI Coding Assistants Part 1: Real-World Use Cases
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. REST Assured: CRUD Framework for API Testing

REST Assured: CRUD Framework for API Testing

Design Pattern for API Testing using Java Rest Assured Library.

By 
Aswani Kumar Avilala user avatar
Aswani Kumar Avilala
DZone Core CORE ·
Updated May. 10, 21 · Tutorial
Likes (16)
Comment
Save
Tweet
Share
17.1K Views

Join the DZone community and get the full member experience.

Join For Free

REST API Cover

REST Assured Java Library - API Testing

REST Assured is an open-source (free) Java library available for testing primarily the RESTful web services. REST Assured is a Java domain-specific language (DSL) for simplifying testing of REST-based web services built on top of HTTP. It supports most commonly used HTTP verbs like GET, POST, PUT/PATCH DELETE, OPTIONS, HEAD which can be used to validate & verify the response of these requests. 

Web API Communication

Web API Communication

Designing Test Cases

Designing Test Cases

Implementation of Test Cases: CRUD Pattern

Step 1: Create a Maven Java project in Eclipse with all the required dependencies in pom.xml as shown below:

                                           Dependency Details
io.rest-assured      --> Rest Assured for testing API interactions(request & response),extract json/xml path.
org.testng           --> Designing the Test Frmework using TestNG Classes. 
com.google.code.gson --> Represent the request body data in the from of java objects like Map <--> JSONformat.
com.github.javafaker --> To supply fake data for testing while sending request.
com.jayway.jsonpath  --> Extract data specifically from JSON file using jayway jsonpath.
XML
 




xxxxxxxxxx
1
56


 
1
<project xmlns="http://maven.apache.org/POM/4.0.0"
2
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0                                                               https://maven.apache.org/xsd/maven-4.0.0.xsd">
4
    <modelVersion>4.0.0</modelVersion>
5
    <groupId>com.rest</groupId>
6
    <artifactId>RestAPITestingProject</artifactId>
7
    <version>0.0.1-SNAPSHOT</version>   
8
    <properties>
9
        <rest.version>4.3.3</rest.version>
10
    </properties>
11
    <dependencies>
12
        <!-- https://mvnrepository.com/artifact/io.rest-assured/rest-assured -->
13
        <dependency>
14
            <groupId>io.rest-assured</groupId>
15
            <artifactId>rest-assured</artifactId>
16
            <version>${rest.version}</version>
17
            <scope>test</scope>
18
        </dependency>
19
        <!-- https://mvnrepository.com/artifact/io.rest-assured/json-path -->
20
        <dependency>
21
            <groupId>io.rest-assured</groupId>
22
            <artifactId>json-path</artifactId>
23
            <version>${rest.version}</version>
24
        </dependency>
25
        <dependency>
26
            <groupId>io.rest-assured</groupId>
27
            <artifactId>xml-path</artifactId>
28
            <version>${rest.version}</version>
29
        </dependency>
30
        <!-- https://mvnrepository.com/artifact/org.testng/testng -->
31
        <dependency>
32
            <groupId>org.testng</groupId>
33
            <artifactId>testng</artifactId>
34
            <version>7.3.0</version>
35
            <scope>test</scope>
36
        </dependency>
37
        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
38
        <dependency>
39
            <groupId>com.google.code.gson</groupId>
40
            <artifactId>gson</artifactId>
41
            <version>2.8.6</version>
42
        </dependency>
43
        <!-- https://mvnrepository.com/artifact/com.github.javafaker/javafaker -->
44
        <dependency>
45
            <groupId>com.github.javafaker</groupId>
46
            <artifactId>javafaker</artifactId>
47
            <version>1.0.2</version>
48
        </dependency>
49
        <!-- https://mvnrepository.com/artifact/com.jayway.jsonpath/json-path -->
50
        <dependency>
51
            <groupId>com.jayway.jsonpath</groupId>
52
            <artifactId>json-path</artifactId>
53
            <version>2.5.0</version>
54
        </dependency>
55
    </dependencies>
56
</project>



Step 2: Design the Routes.java class to register all the available services with end-points as shown below:

Java
 




xxxxxxxxxx
1
24


 
1
package api.engine.endpoints;
2
/**
3
 * 
4
 * @author aswani.kumar.avilala
5
 * Swagger URI --> https://petstore.swagger.io
6
 * Routes class allow the testers to design the end-points for all services that are  available
7
 */
8
public class Routes {
9
    /**
10
     * The base uri is the resource where all the <b>services</b> are running.
11
     */
12
    public static String base_uri  ="https://petstore.swagger.io/v2";
13
    /**
14
     * The post uri route the request to a service to create an user.
15
     */
16
    public static String post_uri  ="/user";
17
    /**
18
     * The get,put,delete uri routes the request to respective services 
19
       to read,update,delete an user using username.
20
     */
21
    public static String get_put_delete_uri="/user/{username}";
22

          
23
}
24

          



Step 3: Design the UserEndpoints.java class to perform Create, Read, Update, Delete requests to the services using the above-created end-points as shown below:

Java
 




x
1
45


 
1
package api.engine.endpoints;
2

          
3
import io.restassured.RestAssured;
4
import io.restassured.http.ContentType;
5
import io.restassured.response.Response;
6
/**
7
 * 
8
 * @author aswani.kumar.avilala
9
 * User Endpoints.java class is designed to to perform Create, Read, Update, Delete requests to the User services 
10
 */
11
public class UserEndpoints {
12
    public static Response createUser(String payload)
13
    {
14
        RestAssured.baseURI=Routes.base_uri;
15
        Response response=RestAssured.
16
                given().contentType(ContentType.JSON).accept(ContentType.JSON).body(payload).
17
                when().post(Routes.post_uri);
18
        return response;
19
    }
20
    public static Response readUser(String userName)
21
    {
22
        RestAssured.baseURI=Routes.base_uri;
23
        Response response=RestAssured.
24
                given().pathParam("username",userName).
25
                when().get(Routes.get_put_delete_uri);
26
        return response;
27
    }
28
    public static Response updateUser(String userName,String payload)
29
    {
30
        RestAssured.baseURI=Routes.base_uri;
31
        Response response=RestAssured.
32
                given().contentType(ContentType.JSON).accept(ContentType.JSON).
33
                pathParam("username",userName).body(payload).
34
                when().put(Routes.get_put_delete_uri);
35
        return response;
36
    }
37
    public static Response deleteUser(String userName)
38
    {
39
        RestAssured.baseURI=Routes.base_uri;
40
        Response response=RestAssured.
41
                given().pathParam("username",userName).
42
                when().delete(Routes.get_put_delete_uri);
43
        return response;
44
    }
45
}



Step 4: Design the User.java class to represents the data structure of the user payload which is in JSON format as shown below:

Java
 




xxxxxxxxxx
1
67


 
1
package api.payload;
2
/**
3
 * 
4
 * @author aswani.kumar.avilala
5
 * User class represents the data structure of the user pay load which is in JSON format
6
 * 
7
 */
8
public class User {
9

          
10
    private Integer userId;
11
    private String userName;
12
    private String firstName;
13
    private String lastName;
14
    private String email;
15
    private String password;
16
    private String phone;
17
    public Integer getUserId() {
18
        return userId;
19
    }
20
    public void setUserId(Integer userId) {
21
        this.userId = userId;
22
    }
23
    public String getUserName() {
24
        return userName;
25
    }
26
    public void setUserName(String userName) {
27
        this.userName = userName;
28
    }
29
    public String getFirstName() {
30
        return firstName;
31
    }
32
    public void setFirstName(String firstName) {
33
        this.firstName = firstName;
34
    }
35
    public String getLastName() {
36
        return lastName;
37
    }
38
    public void setLastName(String lastName) {
39
        this.lastName = lastName;
40
    }
41
    public String getEmail() {
42
        return email;
43
    }
44
    public void setEmail(String email) {
45
        this.email = email;
46
    }
47
    public String getPassword() {
48
        return password;
49
    }
50
    public void setPassword(String password) {
51
        this.password = password;
52
    }
53
    public String getPhone() {
54
        return phone;
55
    }
56
    public void setPhone(String phone) {
57
        this.phone = phone;
58
    }
59
    @Override
60
    public String toString() {
61
        return "User [userId=" + userId + ", userName=" + userName + ", firstName=" + firstName + ", lastName="
62
                + lastName + ", email=" + email + ", password=" + password + ", phone="
63
                + phone + "]";
64
    }
65

          
66
}
67

          



Step 5: Design the TestEndpoints.java class to perform the API Testing for all the services using the TestNG class as shown below:

Java
 




x


 
1
package com.test;
2

          
3
import java.util.HashMap;
4
import java.util.Map;
5
import org.testng.Assert;
6
import org.testng.annotations.BeforeTest;
7
import org.testng.annotations.Test;
8
import com.github.javafaker.Faker;
9
import com.google.gson.Gson;
10
import api.engine.endpoints.UserEndpoints;
11
import api.payload.User;
12
import io.restassured.response.Response;
13
/**
14
 * 
15
 * @author aswani.kumar.avilala
16
 * Perform API Testing for the services using CRUD Design Pattern
17
 */
18
public class TestEndpoints {
19
    Faker faker;
20
    User userPayload;
21

          
22
    @BeforeTest
23
    public void beforeTest()
24
    {
25
        System.out.println("*****************USERNAME UNDER TEST**********************************");
26
        faker=new Faker();
27
        userPayload=new User();
28
        userPayload.setUserId(faker.idNumber().hashCode());
29
        userPayload.setUserName(faker.name().username());
30
        userPayload.setFirstName(faker.name().firstName());
31
        userPayload.setLastName(faker.name().lastName());
32
        userPayload.setEmail(faker.internet().safeEmailAddress());
33
        userPayload.setPassword(faker.internet().password(5,10));
34
        userPayload.setPhone(faker.phoneNumber().cellPhone());
35
        System.out.println("Some Random username genereated by Faker:\t"+userPayload.getUserName());
36
        System.out.println("**********************************************************************");
37
    }
38
    @Test(priority = 1)
39
    public void testPostUser()
40
    {
41
        Map<String,Object> bodyParams=new HashMap<String,Object>();
42
        bodyParams.put("id",userPayload.getUserId());
43
        bodyParams.put("username",userPayload.getUserName());
44
        bodyParams.put("firstName",userPayload.getFirstName());
45
        bodyParams.put("lastName",userPayload.getLastName());
46
        bodyParams.put("email",userPayload.getEmail());
47
        bodyParams.put("password",userPayload.getPassword());
48
        bodyParams.put("phone",userPayload.getPhone());
49
        bodyParams.put("userStatus",0);
50
        String payload=new Gson().toJson(bodyParams);
51
        System.out.println("*************************{POST}***************************************");
52

          
53
        Response response=UserEndpoints.createUser(payload);
54
        response.then().log().all();
55
        Assert.assertEquals(response.getStatusCode(),200);
56
        Assert.assertTrue(response.getStatusLine().contains("OK"));
57

          
58
        System.out.println("**********"  +this.userPayload.getUserName()+" is created ************");
59
    }
60
    @Test(priority = 2)
61
    public void testGetUserByName()
62
    {
63
        System.out.println("*************************{GET}****************************************");
64

          
65
        Response response=UserEndpoints.readUser(this.userPayload.getUserName());
66
        response.then().log().body().statusCode(200);
67

          
68
        System.out.println("************  "+this.userPayload.getUserName()+" is fetched **********");
69
    }
70
    @Test(priority = 3)
71
    public void testUpdateUserByName()
72
    {
73
        Map<String,Object> bodyParams=new HashMap<String,Object>();
74
        bodyParams.put("id",userPayload.getUserId());
75
        bodyParams.put("username",userPayload.getUserName());
76
        /**
77
         * update starts from here based on existing user name
78
         */
79
        bodyParams.put("firstName",userPayload.getFirstName()+" is my first name");
80
        bodyParams.put("lastName",userPayload.getLastName()+" is my last name");
81
        bodyParams.put("email",userPayload.getEmail()+" is my email");
82
        bodyParams.put("password",userPayload.getPassword()+" is my password");
83
        bodyParams.put("phone",userPayload.getPhone()+" is my phone number");
84
        bodyParams.put("userStatus",1);
85
        String payload=new Gson().toJson(bodyParams);
86

          
87
        System.out.println("*************************{UPDATE}************************************");
88

          
89
        Response response=UserEndpoints.updateUser(this.userPayload.getUserName(), payload);
90
        response.then().log().body().statusCode(200);
91

          
92
        Response afterUpdateResponse=UserEndpoints.readUser(this.userPayload.getUserName());
93
        afterUpdateResponse.then().log().body().statusCode(200);
94

          
95

          
96
        System.out.println("*********  "+this.userPayload.getUserName()+" is updated ************");
97
    }
98
    @Test(priority = 4)
99
    public void testDeleteUserByName()
100
    {
101
        System.out.println("*************************{DELETE}************************************");
102

          
103
        Response response=UserEndpoints.deleteUser(this.userPayload.getUserName());
104
        response.then().log().body().statusCode(200);
105

          
106
        System.out.println("********  "+this.userPayload.getUserName()+" is deleted *************");
107
    }
108

          
109
}
110

          



Maven Java Project Structure:

Maven Java Project Structure

***Note: Run the TestEndpoints.java class as TestNG test to observe the below output.

Output:

Java
 




xxxxxxxxxx
1
74


 
1
[RemoteTestNG] detected TestNG version 7.3.0
2
*****************USERNAME UNDER TEST**********************************
3
Some Random username genereated by Faker:   elvin.batz
4
**********************************************************************
5
*************************{POST}***************************************
6
HTTP/1.1 200 OK
7
Date: Tue, 27 Apr 2021 16:56:10 GMT
8
Content-Type: application/json
9
Transfer-Encoding: chunked
10
Connection: keep-alive
11
Access-Control-Allow-Origin: *
12
Access-Control-Allow-Methods: GET, POST, DELETE, PUT
13
Access-Control-Allow-Headers: Content-Type, api_key, Authorization
14
Server: Jetty(9.2.9.v20150224)
15

          
16
{
17
    "code": 200,
18
    "type": "unknown",
19
    "message": "1667689440"
20
}
21
********  elvin.batz is created **************************************
22
*************************{GET}****************************************
23
{
24
    "id": 1667689440,
25
    "username": "elvin.batz",
26
    "firstName": "Marlys",
27
    "lastName": "Kub",
28
    "email": "gilberto.adams@example.com",
29
    "password": "qy3mlpj",
30
    "phone": "1-515-965-2999",
31
    "userStatus": 0
32
}
33
************  elvin.batz is fetched *********************************
34
*************************{UPDATE}************************************
35
{
36
    "code": 200,
37
    "type": "unknown",
38
    "message": "1667689440"
39
}
40
{
41
    "id": 1667689440,
42
    "username": "elvin.batz",
43
    "firstName": "Marlys is my first name",
44
    "lastName": "Kub is my last name",
45
    "email": "gilberto.adams@example.com is my email",
46
    "password": "qy3mlpj is my password",
47
    "phone": "1-515-965-2999 is my phone number",
48
    "userStatus": 1
49
}
50
*********  elvin.batz is updated ************************************
51
*************************{DELETE}************************************
52
{
53
    "code": 200,
54
    "type": "unknown",
55
    "message": "elvin.batz"
56
}
57
********  elvin.batz is deleted *************************************
58
PASSED: testPostUser
59
PASSED: testGetUserByName
60
PASSED: testUpdateUserByName
61
PASSED: testDeleteUserByName
62

          
63
=====================================================================
64
    Default test
65
    Tests run: 4, Failures: 0, Skips: 0
66
=====================================================================
67

          
68

          
69
=====================================================================
70
Default suite
71
Total tests run: 4, Passes: 4, Failures: 0, Skips: 0
72
=====================================================================
73

          
74

          


*** Note: Each time you run the code, a different username is generated by the Java Faker class.

Conclusion:

Hence the above demo represents the completion of design using CRUD pattern, wherein we can modularize and separate the data layer, API calls, test codes. These test cases are completely designed independently of the testing framework. This framework ensures to have code reusability, modularity, and better maintenance of the codes.

REST API Web Protocols API testing Framework

Opinions expressed by DZone contributors are their own.

Related

  • Build a REST API With Just 2 Classes in Java and Quarkus
  • Get Some Rest! A Full API Stack
  • Cypress API Testing: A Detailed Guide
  • API Testing With Cypress

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!