This guide will walk you through setting up and running your first API test with the framework.
Before you begin, ensure you have the following installed:
java -version
mvn -version
git --version
git clone https://github.com/Aditi66/api-automation-framework.git
cd api-automation-framework
mvn clean install
This will:
Take a moment to explore the project structure:
api-automation-framework/
├── src/
│ ├── main/java/org/aditi/api_automation/
│ │ ├── api/User.java # Example API class
│ │ ├── config/ # Configuration management
│ │ ├── requests/ # Request factories
│ │ └── ...
│ ├── main/resources/
│ │ ├── environment/ # Environment configs
│ │ ├── requests/ # JSON templates
│ │ └── response/schemas/ # JSON schemas
│ └── test/
│ ├── java/org/aditi/api_automation/
│ │ ├── steps/UserSteps.java # Example step definitions
│ │ └── ...
│ └── resources/features/
│ └── reqres/User.feature # Example feature file
mvn test
mvn test -Dtest=UserSteps
mvn test -DsuiteXmlFile=testng.xml
Let’s create a simple test to understand the framework workflow.
Create src/main/java/org/aditi/api_automation/api/PostApi.java
:
package org.aditi.api_automation.api;
import io.restassured.response.Response;
import org.aditi.api_automation.config.AppConfig;
import static io.restassured.RestAssured.given;
public class PostApi {
private PostApi() {}
public static Response getPostById(String postId) {
return given()
.baseUri(AppConfig.getConfig().getReqResBaseUrl())
.basePath(AppConfig.getConfig().getReqResBaseApiPath())
.log().ifValidationFails()
.when()
.get("/posts/" + postId)
.then()
.log().ifError()
.extract().response();
}
public static Response createPost(String title, String body, String userId) {
return given()
.baseUri(AppConfig.getConfig().getReqResBaseUrl())
.basePath(AppConfig.getConfig().getReqResBaseApiPath())
.contentType("application/json")
.body("{\"title\":\"" + title + "\",\"body\":\"" + body + "\",\"userId\":" + userId + "}")
.log().ifValidationFails()
.when()
.post("/posts")
.then()
.log().ifError()
.extract().response();
}
}
Create src/test/resources/features/reqres/Post.feature
:
Feature: Post Management
Scenario: Get post by ID
Given I want to retrieve a post
When I request post with ID "1"
Then I should receive a successful response
And the response should contain post details
Scenario: Create a new post
Given I want to create a new post
When I create a post with title "Test Post" and body "Test Body" for user "1"
Then I should receive a successful response
And the response should contain the created post details
Create src/test/java/org/aditi/api_automation/steps/PostSteps.java
:
package org.aditi.api_automation.steps;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import io.restassured.response.Response;
import lombok.extern.slf4j.Slf4j;
import org.aditi.api_automation.api.PostApi;
import org.aditi.api_automation.asserts.ValidateGenericResponse;
@Slf4j
public class PostSteps {
private Response response;
private String postId;
private String title;
private String body;
private String userId;
@Given("I want to retrieve a post")
public void i_want_to_retrieve_a_post() {
// Setup code if needed
}
@When("I request post with ID {string}")
public void i_request_post_with_id(String id) {
this.postId = id;
this.response = PostApi.getPostById(id);
log.info("Response: {}", response.getBody().asString());
}
@Given("I want to create a new post")
public void i_want_to_create_a_new_post() {
// Setup code if needed
}
@When("I create a post with title {string} and body {string} for user {string}")
public void i_create_a_post_with_title_and_body_for_user(String title, String body, String userId) {
this.title = title;
this.body = body;
this.userId = userId;
this.response = PostApi.createPost(title, body, userId);
log.info("Response: {}", response.getBody().asString());
}
@Then("I should receive a successful response")
public void i_should_receive_a_successful_response() {
ValidateGenericResponse.assertThat(response)
.httpStatusCodeIs(200);
}
@Then("the response should contain post details")
public void the_response_should_contain_post_details() {
ValidateGenericResponse.assertThat(response)
.validateJsonPathData("id", Integer.parseInt(postId))
.containsValue("title")
.containsValue("body");
}
@Then("the response should contain the created post details")
public void the_response_should_contain_the_created_post_details() {
ValidateGenericResponse.assertThat(response)
.validateJsonPathData("title", title)
.validateJsonPathData("body", body)
.validateJsonPathData("userId", Integer.parseInt(userId))
.containsValue("id");
}
}
mvn test -Dtest=PostSteps
Let’s create a more sophisticated test using request templates.
Create src/main/resources/requests/post-create.json
:
{
"headers": {
"Content-Type": "application/json"
},
"body": {
"title": "",
"body": "",
"userId": ""
}
}
Add to src/main/java/org/aditi/api_automation/requests/RequestFactory.java
:
@RequestTemplateFile("requests/post-create.json")
RequestSpecBuilder createPostRequest(String title, String body, String userId);
Update PostApi.java
to use the template:
public static Response createPostWithTemplate(String title, String body, String userId) {
return given()
.spec(AppRequests.getRequestFactory()
.createPostRequest(title, body, userId).build())
.baseUri(AppConfig.getConfig().getReqResBaseUrl())
.basePath(AppConfig.getConfig().getReqResBaseApiPath())
.log().ifValidationFails()
.when()
.post("/posts")
.then()
.log().ifError()
.extract().response();
}
Create src/main/resources/response/schemas/post-schema.json
:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"id": {
"type": "number"
},
"title": {
"type": "string"
},
"body": {
"type": "string"
},
"userId": {
"type": "number"
}
},
"required": ["id", "title", "body", "userId"]
}
Update your step definition:
@Then("the response should match the post schema")
public void the_response_should_match_the_post_schema() {
ValidateGenericResponse.assertThat(response)
.matchesSchema("response/schemas/post-schema.json");
}
Add to src/main/java/org/aditi/api_automation/config/ConfigFactory.java
:
@ConfigProperty("POSTS_PATH")
String getPostsPath();
Add to src/main/resources/api.properties
:
POSTS_PATH=/posts
Update your API class:
public static Response getPostById(String postId) {
return given()
.baseUri(AppConfig.getConfig().getReqResBaseUrl())
.basePath(AppConfig.getConfig().getReqResBaseApiPath())
.log().ifValidationFails()
.when()
.get(AppConfig.getConfig().getPostsPath() + "/" + postId)
.then()
.log().ifError()
.extract().response();
}
Create a feature file with data tables:
Feature: Multiple Post Tests
Scenario Outline: Test different posts
Given I want to retrieve a post
When I request post with ID "<postId>"
Then I should receive a successful response
And the response should contain post details
Examples:
| postId |
| 1 |
| 2 |
| 3 |
Feature: Post Management with Background
Background:
Given I have access to the posts API
And I am authenticated
Scenario: Get post by ID
When I request post with ID "1"
Then I should receive a successful response
Create src/main/resources/environment/prod.properties
:
BASE_URL=https://api.production.com/
BASE_API_PATH=/api/v1
mvn test -Dfaasos_env=prod
Add to your test class:
@Before
public void setup() {
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();
}
mvn test -Dlogback.configurationFile=logback-debug.xml
Now that you’ve completed the getting started guide:
Solution: Ensure feature files are in src/test/resources/features/
and step definitions are in src/test/java/org/aditi/api_automation/steps/
Solution: Check that properties are defined in the correct environment file and the @ConfigProperty
annotation is used correctly
Solution: Verify the JSON template file exists and the @RequestTemplateFile
annotation path is correct
Solution: Use tools like JSON Schema Generator to create accurate schemas
Congratulations! You’ve successfully set up and run your first API test with the framework! 🎉