Answer
Best Practices for API Testing
1. Test Independence — Each Test Must Stand Alone
Java
// BAD: test2 depends on test1 creating the user
@Test(dependsOnMethods = "createUser")
public void getUser() { ... }
// GOOD: each test sets up its own data
@Test
public void testGetUser() {
int userId = createTestUser(); // own setup
given().when().get("/api/users/" + userId).then().statusCode(200);
deleteTestUser(userId); // own cleanup
}
2. Use RequestSpecification for Reusability
Java
// BAD: repeat headers in every test
given().header("Authorization", "Bearer " + token)
.header("Content-Type", "application/json")
.when().get("/users");
// GOOD: reuse spec
given(requestSpec).when().get("/users");
3. Validate More Than Just Status Code
Java
// BAD: only check status
.then().statusCode(200);
// GOOD: validate status + body + headers + response time
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.header("Content-Type", containsString("application/json"))
.body("data.id", notNullValue())
.body("data.email", matchesPattern(".+@.+\\..+"))
.time(lessThan(2000L));
4. Always Clean Up Test Data
Java
@AfterMethod
public void cleanup() {
if (createdUserId != null) {
given(requestSpec)
.when()
.delete("/api/users/" + createdUserId);
}
}
5. Use Meaningful Test Names
Java
// BAD
@Test public void test1() { ... }
// GOOD
@Test public void testCreateUser_WithValidData_Returns201() { ... }
@Test public void testCreateUser_WithMissingEmail_Returns400() { ... }
6. Test Both Positive and Negative Scenarios
- ✓✅ Valid data → 200/201
- ✓✅ Missing required field → 400
- ✓✅ Invalid data type → 400/422
- ✓✅ Unauthorized → 401
- ✓✅ Forbidden → 403
- ✓✅ Not found → 404
7. Use Environment Variables for Sensitive Data
Java
// BAD: hardcoded credentials
String token = "abc123secrettoken";
// GOOD: from environment/config
String token = System.getenv("API_TOKEN");
8. Keep Tests Fast and Parallel-Safe
XML
<suite parallel="methods" thread-count="5">
- ✓Use unique test data per thread (randomize emails, IDs)
- ✓Avoid shared mutable state between tests
9. Log on Failure, Not Always
Java
// GOOD: only log when something fails
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();
10. Shift Left — Test APIs Early
- ✓Start testing APIs as soon as the endpoint is deployed
- ✓Don''t wait for the UI to be built
- ✓Run API tests in CI/CD pipeline on every commit
