Table of Contents
π Introduction to REST APIs
A REST (Representational State Transfer) API is an architectural style for designing networked applications. It's a way for different systems to communicate over HTTP in a stateless, scalable, and reliable way. For automation testers, understanding REST APIs is crucial for both UI and API-level testing.
π§© Core Concepts
HTTP Methods
HTTP methods define the action to be performed on a resource.
- GET: Retrieve data from a server.
- POST: Send data to a server to create a new resource.
- PUT: Update an existing resource on the server.
- DELETE: Remove a resource from the server.
HTTP Status Codes
Status codes indicate the result of the HTTP request.
- 2xx (Success): 200 OK, 201 Created
- 3xx (Redirection): 301 Moved Permanently
- 4xx (Client Error): 400 Bad Request, 401 Unauthorized, 404 Not Found
- 5xx (Server Error): 500 Internal Server Error
π§± Request Anatomy & Lifecycle
Every REST call follows the same structure: Method + URL + Headers + Payload. Understanding each piece helps you design focused test cases and troubleshoot failures quickly.
| Component | What It Is | Tester Checklist |
|---|---|---|
| Method | Verb describing the intent (read, create, update, delete). | Assert that the chosen method matches the API contract (e.g. no POST used for reads). |
| Endpoint |
Base URL + path parameters (e.g. /users/{id}).
|
Validate path parameter formats, URL encoding, and versioning
(e.g. /v1/ vs /v2/).
|
| Query Parameters |
Optional filters, pagination, sorting (e.g.
?page=2&limit=20).
|
Test extremes (min, max, null) and ensure parameters cannot be abused for injection. |
| Headers | Metadata for content negotiation, caching, auth, correlation. | Verify required headers, default values, casing, and error messages when missing. |
| Payload (Body) | JSON, XML, multipart, form data sent with POST/PUT/PATCH. | Validate schema, optional fields, array lengths, and server behavior when unexpected fields are present. |
βοΈ HTTP Request Types Compared
Choosing the right verb affects caching, retries, and how the API should behave under load. Use the contract below to design assertions for both happy-path and negative scenarios.
| Method | Typical Use | Safe? | Idempotent? | Common Tests |
|---|---|---|---|---|
| GET | Read data, search, filtering | β | β |
Cache headers present, query combinations, pagination,
conditional GET (If-None-Match).
|
| POST | Create resource, trigger actions | β | β | Required fields, duplicates, retry behavior, server-generated IDs. |
| PUT | Replace resource (full update) | β | β | Repeated requests produce same state, validation for missing optional fields. |
| PATCH | Partial update | β | Depends | JSON merge vs JSON patch semantics, ordering, conflict detection (ETags). |
| DELETE | Remove resource or mark as inactive | β | β | Subsequent deletes return 404/204, cascading deletes, soft delete flags. |
- βSafeβ means the method must not modify server data when used correctly; it has nothing to do with whether parameters sit in the URL or the body.
- Retry-safe methods (GET, PUT, DELETE) should always return the same result no matter how many times they run.
-
For POST-based create endpoints, support an
Idempotency-Keyheader to deduplicate spikes. -
Validate that unsafe methods are protected against accidental
caching (set
Cache-Control: no-storewhere needed).
π‘οΈ Secure vs. Exposed Information by Method
The HTTP verb does not inherently make a call secureβthe transport (HTTPS), payload placement, and caching rules do. Still, different methods have typical exposure patterns that testers should audit.
| Method | Common Exposure Risks | Hardening Techniques |
|---|---|---|
| GET | Query strings appear in browser history, server logs, analytics tools, and intermediary caches. |
Never send credentials/PII in URLs, disable caching with
Cache-Control: no-store for sensitive endpoints,
ensure HTTPS with HSTS.
|
| POST | Payload lives in the body (safer than URL) but can still leak through proxies, verbose logging, or browser autofill. |
Enforce TLS, scrub request/response bodies in logs, apply CSRF
protection, reject missing Content-Type.
|
| PUT/PATCH | Large JSON bodies may include secrets, and partial updates can unintentionally zero-out fields if validation is weak. | Require explicit fields for sensitive attributes, use JSON schema validation, encrypt at rest before persisting. |
| DELETE | Often triggered via GET links in poorly designed UIs, causing CSRF risk and unintended deletions. | Force DELETE via POST/DELETE with anti-CSRF tokens, audit authorization checks, require confirmation workflows in UI. |
- β Use HTTPS everywhere; block plain HTTP requests early.
- β Centralize logging filters to mask tokens, cookies, and PII.
- β Configure caching/CDN rules to prevent storing sensitive responses.
- β Pair method + role verification (e.g., only admins may POST to /users).
- β Document which fields are allowed in URLs to prevent accidental leakage.
π§Ύ Parameters, Headers & Payloads
Path vs Query vs Body
-
Path parameters identify a specific resource
(
/accounts/{id}). They should be validated for type (UUID, int) and URL-encoded. - Query parameters control filtering, pagination, localization. Always test default values and combinations.
- Body payloads hold the state you send to the server. Schema validation and optional fields are critical.
Common Headers
| Header | Role | Tester Focus |
|---|---|---|
Authorization |
Access control (API keys, Bearer tokens, Basic auth). | Expired vs valid tokens, scopes, missing header behavior. |
Content-Type |
Indicates payload format (application/json,
multipart/form-data).
|
Verify server rejects unsupported formats and enforces UTF-8. |
Accept |
Requested response format. | Ensure API negotiates properly (JSON vs XML) and defaults are documented. |
X-Correlation-ID |
Traceability for distributed logs. | Assert that IDs are echoed back and propagated downstream. |
Idempotency-Key |
Prevents duplicate POST processing. | Send identical keys twice and confirm only one resource is created. |
Payload Validation Ideas
- Missing required fields vs empty strings vs null values.
- Boundary testing for numeric fields (min/max), string lengths, enum values.
- Semantic validation: cross-field rules (startDate < endDate, currency + locale alignment).
- Malformed JSON/XML to ensure graceful 400 responses.
π Authentication & Authorization Patterns
Robust API testing exercises success, failure, and expiration paths for each auth scheme. Aim to cover least-privilege scopes, token refresh, and abuse scenarios.
| Method | How It Works | Use Cases | What to Test |
|---|---|---|---|
| API Key |
Static key shared per app, sent as
Authorization: ApiKey <key> or query param.
|
Internal services, server-to-server, low-risk data. | Key rotation, IP allow lists, rate limit enforcement per key. |
| Basic Auth |
Base64 encoded username:password in header.
|
Legacy systems, smoke envs, when using HTTPS only. | Incorrect credentials, lockout thresholds, TLS enforcement. |
| Bearer / JWT |
Signed token with claims (sub, exp, scope) sent as
Authorization: Bearer <jwt>.
|
Modern microservices, SPAs, mobile apps. | Expired tokens, tampered signature, insufficient scopes, clock skew. |
| OAuth 2.0 | Delegated flow (Auth Code, Client Credentials, Device Code) issuing short-lived access tokens + refresh tokens. | Third-party integrations, enterprise APIs, user-consent scenarios. | Token refresh, consent revocation, PKCE enforcement, scope downgrades. |
| HMAC |
Request body + timestamp signed with shared secret, usually
via X-Signature header.
|
Financial APIs, webhook verification. | Replay protection, clock drift tolerance, signature mismatch responses. |
| Mutual TLS | Client presents certificate during TLS handshake; server validates against CA. | B2B integrations, highly regulated industries. | Cert expiration, revoked certs, fallback refusal to plaintext connections. |
- Rotate keys/tokens mid-test and confirm old ones stop working.
- Attempt role escalation (e.g., reader token hitting admin route).
-
Validate error messaging does not leak secrets (
401vs403). -
Check rate-limit headers (
X-RateLimit-Remaining) reset after window.
π οΈ API Testing with Tools
Here are examples of how to perform API requests using popular automation tools.
π Playwright for API Testing
Playwright has built-in capabilities for API testing, allowing you to send requests directly.
β REST Assured for Java
REST Assured is a popular Java library for testing REST APIs.
β Best Practices & Sensitive Data Handling
Designing Test Coverage
- Write contract tests for request/response schemas (e.g., OpenAPI + JSON Schema validation).
- Combine positive, negative, and chaos scenarios (timeouts, throttling, malformed payloads).
- Include performance baselines (95th percentile latency) for critical endpoints.
- Use synthetic data seeding scripts so tests remain deterministic.
Handling Sensitive Data
| Concern | What To Do | Automation Tip |
|---|---|---|
| Secrets in code | Load tokens/keys from vaults (Azure Key Vault, AWS Secrets Manager) via environment variables. | Fail tests if placeholder secrets detected; mask in logs. |
| PII in fixtures | Use anonymized datasets or on-the-fly generators (Faker) with consistent seeds. | Sanitize responses before storing snapshots; redact emails, phone numbers. |
| Data in transit | Enforce HTTPS; block downgrades; validate TLS certificates. |
Add assertions on Strict-Transport-Security and
Content-Security-Policy.
|
| Logs & reports | Mask tokens using regex filters before log aggregation. | Centralize logging via interceptors (REST Assured filters, Playwright hooks). |
Operational Considerations
-
Versioning: Always hit explicit versions
(
/v1/). Automate smoke tests against upcoming versions in parallel. -
Rate Limits: Respect
X-RateLimit-Remaining; throttle your suites to avoid blacklisting. -
Idempotent Retries: Build retry helpers that only
execute on retry-safe methods and inspect
Retry-Afterheaders. - Observability: Capture request/response pairs with correlation IDs so UI test failures can be matched to backend calls.
- Environment Segregation: Separate credentials, base URLs, and data seeds per environment (dev, QA, staging, prod shadow).