How to Use Request Methods (GET, POST, PUT, DELETE) in Rest-Assured
When it comes to API testing, Rest-Assured is a popular and user-friendly library in Java that allows testers and developers to write readable and maintainable code. In this post, we’ll explore the four primary request methods: GET, POST, PUT, and DELETE, and how to implement them using Rest-Assured.
GET Request
A GET request is used to retrieve data from a server. Using Rest-Assured, you can make a GET request like this:
import static io.restassured.RestAssured.*;
public class ApiTest {
public static void main(String[] args) {
given()
.baseUri("https://api.example.com")
.when()
.get("/users")
.then()
.statusCode(200)
.log().body();
}
}
Here, we’re requesting a list of users from “https://api.example.com/users” and checking if the response status is 200 (OK).
POST Request
A POST request is primarily used to submit data to be processed to a specified resource. Here’s how you can make a POST request with Rest-Assured:
import static io.restassured.RestAssured.*;
public class ApiTest {
public static void main(String[] args) {
String jsonData = "{ \"name\": \"John\", \"age\": 30 }";
given()
.baseUri("https://api.example.com")
.header("Content-Type", "application/json")
.body(jsonData)
.when()
.post("/users")
.then()
.statusCode(201)
.log().body();
}
}
In this case, we’re sending a new user’s data to be added to the system and expecting a 201 (Created) status code in response.
PUT Request
A PUT request is utilized to update a current resource or create a new one if it doesn’t exist. Here’s a PUT request example:
import static io.restassured.RestAssured.*;
public class ApiTest {
public static void main(String[] args) {
String updatedData = "{ \"name\": \"Jane\", \"age\": 25 }";
given()
.baseUri("https://api.example.com")
.header("Content-Type", "application/json")
.body(updatedData)
.when()
.put("/users/1")
.then()
.statusCode(200)
.log().body();
}
}
Here, we’re updating the details of the user with ID 1.
DELETE Request
A DELETE request is used to remove a resource from the server. An example with Rest-Assured would be:
import static io.restassured.RestAssured.*;
public class ApiTest {
public static void main(String[] args) {
given()
.baseUri("https://api.example.com")
.when()
.delete("/users/1")
.then()
.statusCode(204)
.log().body();
}
}
In this example, we’re deleting the user with ID 1 and expecting a 204 (No Content) response.
Conclusion
The Rest-Assured library offers an intuitive approach to making various HTTP requests. By mastering the basics of GET, POST, PUT, and DELETE requests, you can confidently test and interact with APIs using Java.