Part 3 — HTTP Methods and CRUD API Testing
Welcome to Part 3 of our comprehensive API Testing Series! In this section, you will transition from basic concepts to writing real-world API test cases. Understanding HTTP methods and CRUD (Create, Read, Update, Delete) operations is the backbone of web service verification and automation.
1. GET API Testing
The GET method is used to retrieve data from a server without modifying anything on the backend. It is idempotent (calling it multiple times produces the same result).
Key Validation Points:
- Status Code: Must return
200 OKfor valid requests. - Response Body: Ensure expected fields and arrays are populated correctly.
- Headers: Validate
Content-Type(e.g.,application/json).
// Rest Assured Example: GET Request
given()
.baseUri("https://api.way2testing.com")
.when()
.get("/users/101")
.then()
.statusCode(200)
.contentType(ContentType.JSON);
2. POST API Testing
The POST request creates a new resource on the server. Unlike GET, POST carries a request payload (body), typically formatted as JSON or XML.
201 Created status code and a unique identifier (ID) in the response payload.
// Rest Assured Example: POST Request
String requestBody = "{\"name\": \"John Doe\", \"role\": \"QA Automation Lead\"}";
given()
.baseUri("https://api.way2testing.com")
.header("Content-Type", "application/json")
.body(requestBody)
.when()
.post("/users")
.then()
.statusCode(201)
.body("name", equalTo("John Doe"));
3. PUT API Testing vs 4. PATCH API Testing
Understanding the difference between PUT and PATCH is a favorite interview question for QA engineers!
- PUT (Full Replace): Overwrites the complete resource. If optional fields are omitted in the body, they may be set to null on the server.
- PATCH (Partial Update): Updates only the specific fields supplied in the request body.
5. DELETE API Testing & 6. Complete CRUD Workflow
A full CRUD Workflow test validates end-to-end data lifecycle management across connected endpoints:
- Create (POST): Submit new entity dynamic payload & captue generated ID.
- Read (GET): Retrieve the entity using the captured ID; verify match.
- Update (PUT/PATCH): Modify attributes and confirm changes.
- Delete (DELETE): Send request to remove entity (verify
200 OKor204 No Content). - Re-Verify (GET): Request entity again and confirm
404 Not Found.
7. Request Headers, 8. Query & 9. Path Parameters
Parameters shape how API requests target resources and handle metadata:
- Headers: Supply metadata such as
Content-Type: application/jsonorAuthorization: Bearer token. - Query Parameters (
?key=value): Used for filtering, sorting, or pagination (e.g.,/users?page=2&role=admin). - Path Parameters (
/users/{id}): Directly locate specific entities via strict route bindings (e.g.,/users/42).
10. Form & Multipart Requests & 11. Session/Cookies
APIs don't just transfer standard JSON. Handling files and legacy session states is vital:
File Upload Example (Multipart):
given()
.multiPart("file", new File("/path/to/test-doc.pdf"))
.when()
.post("/upload")
.then()
.statusCode(200);
Cookies and Sessions:
Pass session IDs or custom cookies using .cookie("session_id", "xyz123") to retain user state during web app session testing.
12. API Response Validation Best Practices
A robust test case checks all four core pillars of an API response:
- HTTP Status Code: Validate precise codes (200, 201, 400, 401, 404, 500).
- Headers: Check safety headers, caching limits, and Content-Type.
- Response Body: Verify exact types, dynamic values, and schema compliance.
- Response Time: Assert latency stays under acceptable SLAs (e.g., < 2000 ms).
Rest Assured Step-by-Step Practical Guides
Explore our targeted step-by-step guides for automating API scenarios with Rest Assured:
1. JSON Request Bodies
Learn how to send JSON payloads using HashMaps, POJOs, Jackson, and external file sources.
2. Dynamic API Requests
Generate runtime dynamic data using Java Faker to avoid duplicated record errors.
3. Validate JSON Fields
Use Hamcrest matchers and JsonPath to assert specific data types and values.
4. Nested JSON & Arrays
Master parsing deep JSON objects, nested lists, and array indexing using JsonPath expressions.
5. Extract Response Values
Extract IDs or Bearer tokens from responses and chain them into downstream API calls.
6. Headers & Content-Type
Assert response headers, server definitions, and character encodings effortlessly.
7. Validate Response Time
Set up SLA assertions using lessThan(2000L) milliseconds in Rest Assured.
8. Handle Empty Responses
Learn strategies for validating HTTP 204 No Content and null body payloads cleanly.
Advanced API Testing: Path Params, File Uploads, Cookies & Validation
Welcome to another deep dive in our API testing series on Way2Testing! In this article, we cover four critical building blocks of REST API automation: targeting specific resources with Path Parameters, submitting Form & Multipart Requests, managing Cookies and Sessions, and performing full Response Validations.
9. Path Parameters: Accessing Resources by ID
Path parameters are variables embedded directly into the URL path, used to locate a specific resource (e.g., a single user, order, or product by its unique ID).
/users/{id}) pinpoint a single resource, whereas query parameters (/users?role=admin) filter or paginate a collection of resources.
Rest Assured Implementation
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
@Test
public void testGetSingleUserByPathParm() {
given()
.baseUri("https://api.way2testing.com")
.pathParam("userId", 502)
.when()
.get("/api/users/{userId}")
.then()
.statusCode(200)
.body("id", equalTo(502))
.body("email", equalTo("user502@way2testing.com"));
}
10. Form and Multipart Requests: Form Data & File Uploads
Not all APIs accept standard application/json payloads. Web applications frequently rely on HTML forms and file upload endpoints that utilize application/x-www-form-urlencoded or multipart/form-data.
1. Form Data Request Example
given()
.baseUri("https://api.way2testing.com")
.contentType("application/x-www-form-urlencoded")
.formParam("username", "testuser")
.formParam("grant_type", "password")
.when()
.post("/oauth/token")
.then()
.statusCode(200);
2. File Upload (Multipart) Example
File fileToUpload = new File("src/test/resources/sample-profile.png");
given()
.baseUri("https://api.way2testing.com")
.multiPart("file", fileToUpload)
.multiPart("description", "Profile Picture Upload")
.when()
.post("/api/v1/user/avatar")
.then()
.statusCode(200)
.body("message", equalTo("File uploaded successfully"));
12. API Response Validation Best Practices
Thorough API automated testing demands multi-layered response assertion. Validating only the status code is never enough!
- Status Codes: 2xx (Success), 4xx (Client Error), 5xx (Server Error).
- Response Headers: Verify
Content-Type, security headers, and tokens. - Response Body: Assert field values, array lengths, and dynamic properties.
- Response Time: Verify SLA limits (e.g., response time < 2 seconds).
Full End-to-End Assertion Example
given()
.baseUri("https://api.way2testing.com")
.when()
.get("/api/v1/orders/1001")
.then()
// 1. Status Code Validation
.statusCode(200)
// 2. Header Validation
.contentType("application/json; charset=utf-8")
.header("Cache-Control", containsString("no-cache"))
// 3. Response Body Assertions
.body("orderId", equalTo(1001))
.body("status", equalTo("DELIVERED"))
.body("items.size()", greaterThan(0))
// 4. Response Time SLA Assertion (< 2000 ms)
.time(lessThan(2000L));
No comments:
Post a Comment