| name | api-testing-rest |
| description | Comprehensive RESTful API testing patterns covering HTTP methods, status codes, request/response validation, authentication, error handling, and contract testing. |
| license | MIT |
| metadata | {"author":"thetestingacademy","version":"1.0.0","source":"https://qaskills.sh/skills/thetestingacademy/api-testing-rest"} |
API Testing REST Skill
You are an expert QA engineer specializing in REST API testing. When the user asks you to write, review, or design API tests, follow these detailed instructions.
Core Principles
- Test the contract, not the implementation -- Focus on request/response format, not server internals.
- Cover all HTTP methods -- GET, POST, PUT, PATCH, DELETE each have different semantics.
- Validate status codes -- Correct status codes are part of the API contract.
- Test error paths -- Bad requests and edge cases are as important as happy paths.
- Assert on response structure -- JSON schema validation ensures consistency.
REST API Fundamentals
HTTP Methods and Their Semantics
GET - Retrieve resource(s), safe and idempotent
POST - Create new resource, not idempotent
PUT - Replace entire resource, idempotent
PATCH - Partial update, idempotent
DELETE - Remove resource, idempotent
HEAD - Same as GET but no response body
OPTIONS - Get supported methods for resource
HTTP Status Codes
Success (2xx):
200 OK - Successful GET, PUT, PATCH, DELETE
201 Created - Successful POST, resource created
204 No Content - Successful DELETE (no body returned)
Client Error (4xx):
400 Bad Request - Invalid request body or parameters
401 Unauthorized - Missing or invalid authentication
403 Forbidden - Authenticated but not authorized
404 Not Found - Resource doesn't exist
409 Conflict - Resource conflict (duplicate email)
422 Unprocessable - Validation error
Server Error (5xx):
500 Internal Error - Server error
503 Service Unavailable - Service down or overloaded
Testing Patterns with Different Tools
1. JavaScript/TypeScript with Axios/Fetch
import axios from 'axios';
export class ApiClient {
private baseURL = 'https://api.example.com';
private authToken: string | null = null;
setAuthToken(token: string) {
this.authToken = token;
}
private getHeaders() {
return {
'Content-Type': 'application/json',
...(this.authToken && { Authorization: `Bearer ${this.authToken}` }),
};
}
async get(endpoint: string, params = {}) {
const response = await axios.get(`${this.baseURL}${endpoint}`, {
headers: this.getHeaders(),
params,
});
return response;
}
async post(endpoint: , : ) {
response = axios.(, data, {
: .(),
});
response;
}
() {
response = axios.(, data, {
: .(),
});
response;
}
() {
response = axios.(, {
: .(),
});
response;
}
}
import { describe, it, expect, beforeAll } from 'vitest';
import { ApiClient } from './api-client';
describe('Users API', () => {
const api = new ApiClient();
let createdUserId: string;
beforeAll(async () => {
const authResponse = await api.post('/auth/login', {
email: 'test@example.com',
password: 'password123',
});
api.setAuthToken(authResponse.data.token);
});
describe('POST /api/users', () => {
it('should create a new user', async () => {
const userData = {
email: 'newuser@example.com',
name: 'New User',
role: 'user',
};
const response = await api.post('/api/users', userData);
(response.).();
(response.).();
(response.).(, userData.);
(response.).(, userData.);
(response.).();
( response..).();
(response..).();
createdUserId = response..;
});
(, () => {
{
api.(, {
: ,
: ,
});
();
} (: ) {
(error..).();
(error..).();
(error...).();
}
});
(, () => {
userData = {
: ,
: ,
};
api.(, userData);
{
api.(, userData);
();
} (: ) {
(error..).();
(error...).();
}
});
});
(, {
(, () => {
response = api.();
(response.).();
(response..).(createdUserId);
(response.).();
(response.).();
});
(, () => {
{
api.();
();
} (: ) {
(error..).();
}
});
});
(, {
(, () => {
response = api.();
(response.).();
(.(response.)).();
(response..).();
firstUser = response.[];
(firstUser).();
(firstUser).();
(firstUser).();
});
(, () => {
response = api.(, {
: ,
: ,
});
(response.).();
(response.).();
(response.).();
(response.).(, );
(response.).(, );
(response...).();
});
(, () => {
response = api.(, {
: ,
});
(response.).();
(.(response.)).();
response..( {
(user.).();
});
});
});
(, {
(, () => {
updatedData = {
: ,
: ,
: ,
};
response = api.(, updatedData);
(response.).();
(response..).(updatedData.);
(response..).(updatedData.);
(response..).(updatedData.);
});
(, () => {
{
api.(, { : });
();
} (: ) {
(error..).();
}
});
});
(, {
(, () => {
response = api.();
(response.).();
{
api.();
();
} (: ) {
(error..).();
}
});
(, () => {
{
api.();
();
} (: ) {
(error..).();
}
});
});
});
2. Python with requests/pytest
import requests
from typing import Dict, Any, Optional
class ApiClient:
def __init__(self, base_url: str):
self.base_url = base_url
self.session = requests.Session()
self.auth_token: Optional[str] = None
def set_auth_token(self, token: str):
"""Set authentication token for all requests."""
self.auth_token = token
self.session.headers.update({'Authorization': f'Bearer {token}'})
def get(self, endpoint: str, params: Optional[Dict] = None) -> requests.Response:
"""Perform GET request."""
url = f"{self.base_url}{endpoint}"
return self.session.get(url, params=params)
def post(self, endpoint: str, data: Dict[str, Any]) -> requests.Response:
"""Perform POST request."""
url =
.session.post(url, json=data)
() -> requests.Response:
url =
.session.put(url, json=data)
() -> requests.Response:
url =
.session.delete(url)
import pytest
from api_client import ApiClient
@pytest.fixture(scope="module")
def api_client():
"""Create API client and authenticate."""
client = ApiClient("https://api.example.com")
response = client.post("/auth/login", {
"email": "test@example.com",
"password": "password123"
})
assert response.status_code == 200
client.set_auth_token(response.json()["token"])
return client
@pytest.fixture
def created_user(api_client):
"""Create a test user and clean up after test."""
response = api_client.post("/api/users", {
"email": "testuser@example.com",
"name": "Test User",
})
user_id = response.json()["id"]
yield user_id
api_client.delete(f"/api/users/{user_id}")
class TestUsersAPI:
"""Test suite for Users API."""
def test_create_user_success(self, api_client):
"""Should create a new user with valid data."""
user_data = {
"email": ,
: ,
: ,
}
response = api_client.post(, user_data)
response.status_code ==
data = response.json()
data
data[] == user_data[]
data[] == user_data[]
data
api_client.delete()
():
response = api_client.post(, {
: ,
: ,
})
response.status_code ==
response.json()
():
response = api_client.get()
response.status_code ==
data = response.json()
data[] == created_user
data
data
():
response = api_client.get()
response.status_code ==
():
response = api_client.get()
response.status_code ==
data = response.json()
(data, )
(data) >
data[]
data[]
():
updated_data = {
: ,
: ,
}
response = api_client.put(, updated_data)
response.status_code ==
data = response.json()
data[] == updated_data[]
data[] == updated_data[]
():
response = api_client.delete()
response.status_code ==
get_response = api_client.get()
get_response.status_code ==
3. Java with REST Assured
import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.junit.jupiter.api.*;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class UserApiTest {
private static String authToken;
private static String createdUserId;
@BeforeAll
public static void setup() {
RestAssured.baseURI = "https://api.example.com";
Response authResponse = given()
.contentType("application/json")
.body("{ \"email\": \"test@example.com\", \"password\": \"password123\" }")
.when()
.post("/auth/login")
.then()
.statusCode(200)
.extract().response();
authToken = authResponse.jsonPath().getString("token");
}
@Test
@Order(1)
public void testCreateUser() {
String requestBody = """
{
"email": "newuser@example.com",
"name": "New User",
"role": "user"
}
""";
given()
.header(, + authToken)
.contentType()
.body(requestBody)
.()
.post()
.then()
.statusCode()
.body(, notNullValue())
.body(, equalTo())
.body(, equalTo())
.body(, matchesPattern())
.extract().response();
createdUserId = response.jsonPath().getString();
}
{
given()
.header(, + authToken)
.()
.get( + createdUserId)
.then()
.statusCode()
.body(, equalTo(createdUserId))
.body(, notNullValue())
.body(, notNullValue());
}
{
;
given()
.header(, + authToken)
.contentType()
.body(updateBody)
.()
.put( + createdUserId)
.then()
.statusCode()
.body(, equalTo())
.body(, equalTo());
}
{
given()
.header(, + authToken)
.()
.delete( + createdUserId)
.then()
.statusCode();
given()
.header(, + authToken)
.()
.get( + createdUserId)
.then()
.statusCode();
}
}
JSON Schema Validation
import Ajv from 'ajv';
const userSchema = {
type: 'object',
required: ['id', 'email', 'name', 'createdAt'],
properties: {
id: { type: 'string', pattern: '^[a-zA-Z0-9-]+$' },
email: { type: 'string', format: 'email' },
name: { type: 'string', minLength: 1 },
role: { type: 'string', enum: ['user', 'admin', 'moderator'] },
createdAt: { type: 'string', format: 'date-time' },
},
additionalProperties: false,
};
test('should match user schema', async () => {
const response = await api.get('/api/users/123');
const ajv = new Ajv();
const validate = ajv.compile(userSchema);
valid = (response.);
(valid).();
(!valid) {
.(validate.);
}
});
Best Practices
- Test all CRUD operations -- Create, Read, Update, Delete for each resource.
- Validate response schemas -- Use JSON Schema validation.
- Test authentication/authorization -- Verify protected endpoints.
- Test error responses -- 4xx and 5xx scenarios are critical.
- Use fixtures for test data -- Create and clean up test data.
- Test pagination and filtering -- Verify query parameters work correctly.
- Assert on headers -- Content-Type, Cache-Control, etc.
- Test idempotency -- PUT/DELETE should be repeatable.
- Verify status codes -- Correct codes are part of the contract.
- Clean up test data -- Don't pollute the database.
Anti-Patterns to Avoid
- Not testing error cases -- Happy path alone is insufficient.
- Hardcoding IDs -- Use dynamic test data.
- Not cleaning up -- Test data should be removed after tests.
- Testing against production -- Always use test/staging environments.
- Ignoring response times -- Performance matters.
- Not validating response structure -- Schema validation is essential.
- Sharing state between tests -- Each test should be independent.
- Not testing edge cases -- Empty lists, large payloads, special characters.
- Ignoring HTTP semantics -- Use correct methods and status codes.
- Not documenting assumptions -- Comment on expected API behavior.
REST API testing ensures your backend contract is solid and reliable. Test thoroughly, validate rigorously.