Learn API testing techniques and web service validation.
Learn API testing techniques and web service validation.
Understand the basics of API testing and its importance in modern applications
Content by: Paras Dadhania
Software Testing & QA Specialist
API testing is a type of software testing that involves testing application programming interfaces (APIs) directly and as part of integration testing to determine if they meet expectations for functionality, reliability, performance, and security.
// Functional Testing
const functionalTests = {
"Valid Input": "Test with valid request data",
"Invalid Input": "Test with invalid request data",
"Boundary Values": "Test edge cases and limits",
"Error Handling": "Test error responses and codes",
"Business Logic": "Test business rules and workflows"
};
// Non-Functional Testing
const nonFunctionalTests = {
"Performance": "Response time and throughput",
"Load Testing": "API behavior under normal load",
"Stress Testing": "API behavior under extreme load",
"Security Testing": "Authentication and authorization",
"Reliability": "API availability and consistency"
};
// API Testing Levels
const testingLevels = {
"Unit Level": "Individual API endpoints",
"Integration Level": "API interactions with other systems",
"End-to-End Level": "Complete API workflows",
"Contract Level": "API contract validation"
};
Test your understanding of this topic:
Master REST API testing techniques and best practices
Content by: Yash Sanghavi
Software Testing & QA Specialist
// GET Request Example
GET https://api.example.com/users/123
Headers:
Authorization: Bearer token123
Accept: application/json
Response:
{
"id": 123,
"name": "John Doe",
"email": "john@example.com",
"status": "active"
}
// POST Request Example
POST https://api.example.com/users
Headers:
Content-Type: application/json
Authorization: Bearer token123
Body:
{
"name": "Jane Smith",
"email": "jane@example.com",
"password": "securepass123"
}
Response:
{
"id": 124,
"name": "Jane Smith",
"email": "jane@example.com",
"status": "active",
"created_at": "2024-01-15T10:30:00Z"
}
// PUT Request Example
PUT https://api.example.com/users/123
Headers:
Content-Type: application/json
Authorization: Bearer token123
Body:
{
"name": "John Updated",
"email": "john.updated@example.com"
}
Response:
{
"id": 123,
"name": "John Updated",
"email": "john.updated@example.com",
"status": "active",
"updated_at": "2024-01-15T11:00:00Z"
}
// DELETE Request Example
DELETE https://api.example.com/users/123
Headers:
Authorization: Bearer token123
Response:
{
"message": "User deleted successfully",
"deleted_at": "2024-01-15T11:30:00Z"
}
// Positive Test Cases
const positiveTestCases = [
{
"Test": "GET /users - Valid request",
"Request": "GET https://api.example.com/users",
"Expected": "200 OK, List of users"
},
{
"Test": "POST /users - Create valid user",
"Request": "POST with valid user data",
"Expected": "201 Created, User object with ID"
},
{
"Test": "PUT /users/123 - Update existing user",
"Request": "PUT with updated data",
"Expected": "200 OK, Updated user object"
}
];
// Negative Test Cases
const negativeTestCases = [
{
"Test": "GET /users/999 - Non-existent user",
"Request": "GET https://api.example.com/users/999",
"Expected": "404 Not Found"
},
{
"Test": "POST /users - Invalid data",
"Request": "POST with missing required fields",
"Expected": "400 Bad Request, Validation errors"
},
{
"Test": "PUT /users/123 - Unauthorized",
"Request": "PUT without valid token",
"Expected": "401 Unauthorized"
}
];
// Edge Cases
const edgeTestCases = [
{
"Test": "GET /users - Empty result",
"Request": "GET with filter that returns no results",
"Expected": "200 OK, Empty array"
},
{
"Test": "POST /users - Duplicate email",
"Request": "POST with existing email",
"Expected": "409 Conflict, Duplicate email error"
},
{
"Test": "PUT /users/123 - Large payload",
"Request": "PUT with very large data",
"Expected": "413 Payload Too Large"
}
];
Test your understanding of this topic:
Learn SOAP API testing techniques and XML-based web services
Content by: Paras Dadhania
Software Testing & QA Specialist
// SOAP Request
POST /soap/UserService HTTP/1.1
Host: api.example.com
Content-Type: text/xml; charset=utf-8
SOAPAction: "getUser"
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<Authentication>
<Token>abc123token</Token>
</Authentication>
</soap:Header>
<soap:Body>
<getUser xmlns="http://example.com/userservice">
<userId>123</userId>
</getUser>
</soap:Body>
</soap:Envelope>
// SOAP Response
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<getUserResponse xmlns="http://example.com/userservice">
<user>
<id>123</id>
<name>John Doe</name>
<email>john@example.com</email>
<status>active</status>
</user>
</getUserResponse>
</soap:Body>
</soap:Envelope>
// SOAP Fault Response
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<soap:Fault>
<faultcode>soap:Client</faultcode>
<faultstring>Invalid user ID</faultstring>
<detail>
<ErrorCode>INVALID_USER_ID</ErrorCode>
<ErrorMessage>User ID must be a positive integer</ErrorMessage>
</detail>
</soap:Fault>
</soap:Body>
</soap:Envelope>
Test your understanding of this topic:
Master Postman and other API testing tools for comprehensive API testing
Content by: Yash Sanghavi
Software Testing & QA Specialist
// Postman Test Script Examples
// Basic Response Validation
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
pm.test("Response time is less than 2000ms", function () {
pm.expect(pm.response.responseTime).to.be.below(2000);
});
pm.test("Response has required fields", function () {
const jsonData = pm.response.json();
pm.expect(jsonData).to.have.property('id');
pm.expect(jsonData).to.have.property('name');
pm.expect(jsonData).to.have.property('email');
});
// JSON Schema Validation
pm.test("Response matches schema", function () {
const schema = {
"type": "object",
"properties": {
"id": {"type": "number"},
"name": {"type": "string"},
"email": {"type": "string", "format": "email"},
"status": {"type": "string", "enum": ["active", "inactive"]}
},
"required": ["id", "name", "email", "status"]
};
pm.response.to.have.jsonSchema(schema);
});
// Environment Variables
pm.test("Set user ID for next request", function () {
const jsonData = pm.response.json();
pm.environment.set("user_id", jsonData.id);
});
// Dynamic Data Generation
pm.test("Generate test data", function () {
const randomEmail = pm.variables.replace("{{$randomEmail}}");
const randomName = pm.variables.replace("{{$randomFullName}}");
pm.environment.set("test_email", randomEmail);
pm.environment.set("test_name", randomName);
});
// Authentication Token Handling
pm.test("Extract and store auth token", function () {
const jsonData = pm.response.json();
pm.environment.set("auth_token", jsonData.token);
});
// Collection Runner Scripts
pm.test("API Performance Test", function () {
pm.expect(pm.response.responseTime).to.be.below(1000);
pm.expect(pm.response.code).to.be.oneOf([200, 201]);
});
// Error Handling Tests
pm.test("Handle error responses", function () {
if (pm.response.code >= 400) {
const jsonData = pm.response.json();
pm.expect(jsonData).to.have.property('error');
pm.expect(jsonData).to.have.property('message');
}
});
Test your understanding of this topic:
Learn how to automate API testing using various frameworks and tools
Content by: Paras Dadhania
Software Testing & QA Specialist
// RestAssured Maven Dependency
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.3.2</version>
</dependency>
// Basic RestAssured Test
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class APITest {
@Test
public void testGetUser() {
given()
.baseUri("https://api.example.com")
.header("Authorization", "Bearer token123")
.when()
.get("/users/123")
.then()
.statusCode(200)
.body("id", equalTo(123))
.body("name", notNullValue())
.body("email", containsString("@"))
.time(lessThan(2000L));
}
@Test
public void testCreateUser() {
String userJson = """
{
"name": "John Doe",
"email": "john@example.com",
"password": "securepass123"
}
""";
given()
.baseUri("https://api.example.com")
.contentType("application/json")
.body(userJson)
.when()
.post("/users")
.then()
.statusCode(201)
.body("id", notNullValue())
.body("name", equalTo("John Doe"))
.body("email", equalTo("john@example.com"))
.body("status", equalTo("active"));
}
@Test
public void testUpdateUser() {
String updateJson = """
{
"name": "John Updated",
"email": "john.updated@example.com"
}
""";
given()
.baseUri("https://api.example.com")
.contentType("application/json")
.body(updateJson)
.when()
.put("/users/123")
.then()
.statusCode(200)
.body("name", equalTo("John Updated"))
.body("email", equalTo("john.updated@example.com"));
}
@Test
public void testDeleteUser() {
given()
.baseUri("https://api.example.com")
.when()
.delete("/users/123")
.then()
.statusCode(200)
.body("message", equalTo("User deleted successfully"));
}
}
// Data-Driven API Testing
@DataProvider(name = "userData")
public Object[][] getUserData() {
return new Object[][] {
{"John Doe", "john@example.com", "pass123"},
{"Jane Smith", "jane@example.com", "pass456"},
{"Bob Johnson", "bob@example.com", "pass789"}
};
}
@Test(dataProvider = "userData")
public void testCreateUserWithData(String name, String email, String password) {
String userJson = String.format("""
{
"name": "%s",
"email": "%s",
"password": "%s"
}
""", name, email, password);
given()
.baseUri("https://api.example.com")
.contentType("application/json")
.body(userJson)
.when()
.post("/users")
.then()
.statusCode(201)
.body("name", equalTo(name))
.body("email", equalTo(email));
}
Test your understanding of this topic:
Continue your learning journey and master the next set of concepts.
Continue to Module 6