API Automation with REST Assured
In today’s fast-paced development environments, API testing is a critical part of ensuring application functionality. REST Assured is a powerful Java-based library that simplifies the process of automating REST API tests. It allows developers and testers to write readable, maintainable, and efficient test scripts with minimal setup.
Here’s a step-by-step guide to API automation using REST Assured.
What is REST Assured?
REST Assured is an open-source library for testing RESTful web services. Built on top of Java, it integrates well with testing frameworks like JUnit or TestNG and supports BDD-style syntax for readable test cases.
Add REST Assured to Your Project
For Maven users, add the following dependency in your pom.xml:
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.3.0</version>
<scope>test</scope>
</dependency>
You may also include dependencies for TestNG or JUnit based on your testing framework.
Write a Simple GET Request Test
import io.restassured.RestAssured;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
import org.testng.annotations.Test;
public class ApiTest {
@Test
public void testGetUsers() {
RestAssured.baseURI = "https://reqres.in/api";
given().
when().
get("/users?page=2").
then().
statusCode(200).
body("data[0].id", equalTo(7));
}
}
This test:
- Sends a GET request
- Verifies status code is 200
- Validates response content
POST Request with Payload
@Test
public void testCreateUser() {
String payload = "{ \"name\": \"John\", \"job\": \"developer\" }";
given().
header("Content-Type", "application/json").
body(payload).
when().
post("/users").
then().
statusCode(201).
body("name", equalTo("John")).
body("job", equalTo("developer"));
}
This test checks whether a new user is successfully created via POST.
Other HTTP Methods
REST Assured supports:
PUT – to update resources
DELETE – to remove resources
PATCH – for partial updates
Each method follows a similar syntax pattern.
Best Practices
- Use Base URI and path parameters to avoid repetition
- Use data-driven testing with TestNG or JUnit
- Add logging (log().all()) for debugging failed tests
- Integrate with CI/CD pipelines for continuous testing
Conclusion
REST Assured makes API automation easy and effective for Java developers. Its readable syntax and seamless integration with Java testing frameworks make it a top choice for RESTful API testing. With REST Assured in your toolkit, you can confidently validate your APIs and improve overall application quality.
Learn Fullstack Software Testing Tools Training in Hyderabad
Read More:
Using Allure for Test Reporting
Continuous Testing with GitHub Actions
Understanding the Basics of Appium for Mobile Testing
Choosing the Right Automation Tool for Your Project
Visit our IHub Talent Training Institute
Comments
Post a Comment