Showing posts with label API Test Automation Framework. Show all posts
Showing posts with label API Test Automation Framework. Show all posts

First Rest Assured Code to Test API

 



To test any API using Rest Assured, you need to follow these steps:

1. Setup

Before writing any Rest Assured test, we need to set up:
  • A Java project (Maven or Gradle is preferred).
  • Add the Rest Assured dependency in pom.xml or build.gradle.
  • Optionally add TestNG or JUnit as the testing framework.

2. Import Required Classes
  • In a Rest Assured test, you typically import:
  • Rest Assured methods for sending requests.
  • Assertions from TestNG/JUnit to validate the response.

3. Define the Base URI
  • You specify the API endpoint you want to test.
  • Example: If you are testing a sample API like https://reqres.in/api/users, this becomes your base URI.

4. Send a Request

You make a request to the API:
  • GET request to fetch data.
  • POST request to send data.
  • PUT/PATCH request to update data.
  • DELETE request to remove data.
The request can include headers, query parameters, or body depending on the API requirements.


5. Capture the Response

When the API responds, Rest Assured stores details such as:
  • Status code (200, 201, 400, 404, etc.)
  • Response body (JSON, XML, text, etc.)
  • Headers (content-type, server info, etc.)
  • Response time

6. Validate the Response

Assertions are applied to verify if the API behaves as expected. Typical checks are:
  • Status code is correct (e.g., 200 for success).
  • Response body contains expected values (e.g., user name, ID).
  • Headers are correct (e.g., content-type is application/json).
  • Response time is within acceptable limits.

7. Organize into a Test Case

The above steps (setup → request → response → validation) are wrapped inside a test method using TestNG or JUnit. This test can then be executed like any other automated test case.

Below we are automating GET API from reqres.in 

























Add Maven Dependencies

<dependencies>
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>5.4.0</version>
        <scope>test</scope>
    </dependency>
<dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>7.9.0</version> <!-- Latest version -->
    <scope>test</scope>
  </dependency>
</dependencies>



Take a simple example of API: 
https://reqres.in/api/users


Rest Assured Code:

To get Status code of given API:

	@Test
	public void test() {
		
		Response response = RestAssured.get("https://reqres.in/api/users?page=2");
		System.out.println(response.statusCode());
		
	}



To log all response on console:

	@Test
	public void test1() {
		RestAssured.baseURI = "https://reqres.in/api/";
		RestAssured.given().get("users?page=2").then().statusCode(200).log().all();
	}



Code Explanation:


LinePurpose
baseURISets the base URL.
given()Prepares request specification.
when().get()Triggers GET request.
then()Begins response verification.
log().all()Logs complete request/response.
statusCode(200)Asserts HTTP status.


Suggested Posts:

1. Execute Playwright Script on Chrome Browser
2. How to extract Response in Rest Assured by JSONPath
3. Test PUT API in RestAssured
4. Test DELETE API in RestAssured
5. How to Test Status Line of API by RestAssured

Rest Assured Framework Overview for API Testing




What is Rest Assured?

  • Rest Assured is a Java-based library designed to simplify the process of testing REST APIs.
  • Instead of manually sending HTTP requests and parsing responses, Rest Assured provides a fluent and easy-to-use API to handle all of that.
  • It integrates smoothly with JUnit or TestNG, so it fits into existing test automation frameworks.
  • It is widely used in test automation frameworks for API testing, especially in Java environments.

Why Do We Need Rest Assured?

When testing APIs, we need to:
  • Send Requests → GET, POST, PUT, DELETE, etc.
  • Validate Responses → status codes, headers, response time, and body data.
  • Handle Data Formats → JSON, XML, or plain text.
Without a framework, doing all this means writing a lot of boilerplate code (like setting up HTTP clients, handling JSON parsing, etc.).


Where It Fits in Testing
  • Functional Testing → Ensures API endpoints return correct responses.
  • Regression Testing → Quickly retest APIs when code changes.
  • Integration Testing → Check how APIs interact with databases, services, or other systems.
  • End-to-End Testing → APIs can be tested as part of larger workflows.

Why Rest Assured vs Other Options?

  • Compared to using Postman → Rest Assured allows automation, integration with CI/CD, and reusable test suites.
  • Compared to writing raw HTTP requests in Java → Rest Assured removes complexity by handling requests, responses, and validations out of the box.










Rest Assured Testing Lifecycle

1. Test Planning & Setup
  • Identify the API endpoints you want to test (e.g., /login, /users, /orders).
  • Understand the request types (GET, POST, PUT, DELETE, etc.).
  • Gather information about:
Base URI (server address)
Authentication (Basic, OAuth, etc.)
Request/response formats (JSON, XML).


2. Request Specification
  • Define the base URI and common headers (like Content-Type).
  • Prepare request payloads if the API requires input (e.g., JSON for POST requests).
  • Add authentication details if needed.
This step ensures consistency and avoids repeating setup for every test.


3. Send the Request
  • Use Rest Assured to send an HTTP request (GET, POST, PUT, DELETE, etc.) to the server.
  • The request is executed, and the API server processes it.

4. Receive the Response
  • Capture the response sent back by the server.
  • This includes:
Status code (200, 400, 404, 500, etc.)
Response body (JSON/XML data)
Response headers (content type, server details, etc.)
Response time (performance aspect).


5. Validation & Assertions
  • Verify the status code (e.g., 200 for success, 201 for resource creation).
  • Validate headers (e.g., Content-Type is application/json).
  • Assert on the response body:
Correct data returned?
Fields present or missing?
Values match expectations?


6. Test Reporting
  • Test results are logged (pass/fail).
  • If integrated with frameworks (TestNG/JUnit), detailed reports are generated.
  • Can also be hooked into CI/CD pipelines (like Jenkins, GitHub Actions) for automated reporting.

7. Test Maintenance & Reuse
  • Reuse request specifications for multiple test cases.
  • Update tests when API contracts change.
  • Keep validations flexible so they remain maintainable as APIs evolve.

The request is executed, and the API server processes it.

Common Use Cases

  • Functional testing of REST APIs
  • Integration testing
  • Regression testing
  • Automated tests in CI/CD pipelines
  • Validation of API contracts (schema testing)

Technologies/Tools Rest Assured Works Well With

  • Testing Frameworks: JUnit, TestNG, Cucumber
  • Build Tools: Maven, Gradle
  • Serialization Libraries: Jackson, Gson
  • Mocking Tools: WireMock, Mockito
  • CI Tools: Jenkins, GitHub Actions, GitLab CI

How Rest Assured Fits into Test Automation Framework

Rest Assured can be part of the test layer in a test automation framework where:

  • Test data is read from external sources (CSV, Excel, JSON, DB).
  • Test cases are written in BDD format (with Cucumber).
  • Assertions are performed on API responses.
  • Reports are generated using tools like Allure or Extent Reports.


Advantages

  • Simplifies REST API testing in Java
  • Readable, maintainable syntax
  • Rich feature set for validation and assertions
  • Seamless integration with Java ecosystem

Limitations

  • Supports only REST APIs (not SOAP)
  • Tied to Java ecosystem (not suitable for Python, JavaScript, etc.)
  • UI-less (not meant for front-end automation)


Suggested Posts:

1. Features of RestAssured Framework
2. First RestAssured Code to Test API
3. Test PUT API in RestAssured
4. Test DELETE API in RestAssured
5. How to Test Status Line of API by RestAssured