Guide to Rest Assured in Java

Introduction to REST-assured

REST-assured is a popular Java library used for testing and validating RESTful APIs. It simplifies the process of making HTTP requests and assertions on the responses. This guide covers the installation, basic usage, advanced features, and various use cases of REST-assured using the latest version.

Installation

Adding REST-assured to Your Project

To use REST-assured, add the following dependency to your pom.xml if you're using Maven:

<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>4.5.1</version> <!-- or the latest version -->
    <scope>test</scope>
</dependency>

For Gradle:

testImplementation 'io.rest-assured:rest-assured:4.5.1'

Getting Started with REST-assured

Basic GET Request

A basic GET request can be made using REST-assured to fetch data from a REST API.

import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class BasicGetExample {
    public static void main(String[] args) {
        get("https://jsonplaceholder.typicode.com/posts/1")
                .then()
                .statusCode(200)
                .body("userId", equalTo(1))
                .body("id", equalTo(1))
                .body("title", notNullValue());
    }
}

Explanation: This example sends a GET request to fetch a post by ID from a placeholder API and verifies the status code and response body using Hamcrest matchers.

Output:

No output if assertions pass.

Basic POST Request

A basic POST request can be made using REST-assured to send data to a REST API.

import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
import org.json.JSONObject;

public class BasicPostExample {
    public static void main(String[] args) {
        JSONObject requestParams = new JSONObject();
        requestParams.put("title", "foo");
        requestParams.put("body", "bar");
        requestParams.put("userId", 1);

        given()
                .header("Content-Type", "application/json")
                .body(requestParams.toString())
        .when()
                .post("https://jsonplaceholder.typicode.com/posts")
        .then()
                .statusCode(201)
                .body("title", equalTo("foo"))
                .body("body", equalTo("bar"))
                .body("userId", equalTo(1));
    }
}

Explanation: This example sends a POST request to create a new post on the placeholder API, verifying the status code and response body.

Output:

No output if assertions pass.

Advanced Features

Adding Headers and Query Parameters

You can add headers and query parameters to your requests.

import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class HeadersAndQueryParamsExample {
    public static void main(String[] args) {
        given()
                .header("Accept", "application/json")
                .queryParam("userId", 1)
        .when()
                .get("https://jsonplaceholder.typicode.com/posts")
        .then()
                .statusCode(200)
                .body("size()", greaterThan(0));
    }
}

Explanation: This example sends a GET request with a header and query parameter, verifying that the response contains at least one post.

Output:

No output if assertions pass.

Basic Authentication

REST-assured supports basic authentication.

import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class BasicAuthExample {
    public static void main(String[] args) {
        given()
                .auth().basic("username", "password")
        .when()
                .get("https://jsonplaceholder.typicode.com/posts/1")
        .then()
                .statusCode(200);
    }
}

Explanation: This example demonstrates how to use basic authentication for a GET request.

Output:

No output if assertions pass.

Extracting Values from Responses

You can extract values from responses for further processing.

import static io.restassured.RestAssured.*;
import io.restassured.response.Response;

public class ExtractValuesExample {
    public static void main(String[] args) {
        Response response = get("https://jsonplaceholder.typicode.com/posts/1");

        int userId = response.path("userId");
        String title = response.path("title");

        System.out.println("User ID: " + userId);
        System.out.println("Title: " + title);
    }
}

Explanation: This example sends a GET request and extracts the userId and title fields from the response, printing them to the console.

Output:

User ID: 1
Title: sunt aut facere repellat provident occaecati excepturi optio reprehenderit

Working with JSON and XML

Validating JSON Response

You can validate JSON responses using Hamcrest matchers.

import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class JsonValidationExample {
    public static void main(String[] args) {
        get("https://jsonplaceholder.typicode.com/posts/1")
                .then()
                .statusCode(200)
                .body("userId", equalTo(1))
                .body("id", equalTo(1))
                .body("title", equalTo("sunt aut facere repellat provident occaecati excepturi optio reprehenderit"));
    }
}

Explanation: This example validates specific fields in a JSON response.

Output:

No output if assertions pass.

Validating XML Response

You can validate XML responses using Hamcrest matchers and XPath expressions.

import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class XmlValidationExample {
    public static void main(String[] args) {
        get("https://www.w3schools.com/xml/note.xml")
                .then()
                .statusCode(200)
                .body("note.to", equalTo("Tove"))
                .body("note.from", equalTo("Jani"));
    }
}

Explanation: This example validates specific fields in an XML response using XPath expressions.

Output:

No output if assertions pass.

Handling Different HTTP Methods

PUT Request

import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
import org.json.JSONObject;

public class PutExample {
    public static void main(String[] args) {
        JSONObject requestParams = new JSONObject();
        requestParams.put("title", "foo");
        requestParams.put("body", "bar");
        requestParams.put("userId", 1);

        given()
                .header("Content-Type", "application/json")
                .body(requestParams.toString())
        .when()
                .put("https://jsonplaceholder.typicode.com/posts/1")
        .then()
                .statusCode(200)
                .body("title", equalTo("foo"))
                .body("body", equalTo("bar"))
                .body("userId", equalTo(1));
    }
}

Explanation: This example sends a PUT request to update an existing post, verifying the status code and response body.

Output:

No output if assertions pass.

DELETE Request

import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class DeleteExample {
    public static void main(String[] args) {
        delete("https://jsonplaceholder.typicode.com/posts/1")
                .then()
                .statusCode(200);
    }
}

Explanation: This example sends a DELETE request to remove a post and verifies the status code.

Output:

No output if assertions pass.

Working with Files

Uploading a File

You can upload files using REST-assured.

import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
import java.io.File;

public class FileUploadExample {
    public static void main(String[] args) {
        File file = new File("path/to/file.txt");

        given()
                .multiPart("file", file)
        .when()
                .post("https://jsonplaceholder.typicode.com/upload")
        .then()
                .statusCode(200);
    }
}

Explanation: This example demonstrates how to upload a file using a POST request.

Output:

No output if assertions pass.

Downloading a File

You can download files and save them using REST-assured.

import static io.restassured.RestAssured.*;
import java.io.InputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileDownloadExample {
    public static void main(String[] args) throws IOException {
        InputStream inputStream = get("https://jsonplaceholder.typicode.com/image.jpg").asInputStream();
        FileOutputStream outputStream = new FileOutputStream("downloaded_image.jpg");

        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }

        inputStream.close();
        outputStream.close();
    }
}

Explanation: This example demonstrates how to download a file and save it to the local file system.

Output:

No output if assertions pass.

Conclusion

REST-assured is a powerful library for testing and validating RESTful APIs in Java. This guide covered the basics of making GET and POST requests, adding headers and query parameters, basic authentication, extracting values from responses, handling JSON and XML responses, and performing PUT and DELETE requests. Additionally, it demonstrated working with files, including uploading and downloading files. 

By leveraging REST-assured, you can efficiently test and validate your APIs, ensuring they function correctly. For more detailed information and advanced features, refer to the official RestAssured documentation.

Comments