Lesson 9 of 9 · 24m
Testing and Observability for API Operations
Test behavior at the HTTP boundary, verify contract drift in CI, and instrument APIs so production tells you what clients are actually experiencing.
An API can pass every unit test and still be unusable because the routes are wrong, middleware order mutates responses, serialization leaks, or auth happens after rate limiting in one endpoint and before it in another. API testing belongs at the boundary where clients experience the system.
Test HTTP behavior, not framework trivia
Feature tests should exercise real requests: method, path, headers, payload, status, response body, and important side effects.
it('prevents another tenant from reading an invoice', function () {
$user = User::factory()->forTenant('tenant_a')->create();
$invoice = Invoice::factory()->forTenant('tenant_b')->create();
actingAsApiUser($user)
->getJson('/v1/invoices/' . $invoice->publicId)
->assertStatus(404);
});That test is worth more than five isolated controller mocks because it exercises routing, auth, object lookup, policy logic, serialization, and error shape together.
Contract-test the important promises
At minimum, test:
- success shape for every public endpoint; validation failure shape and status
- unauthenticated and unauthorized behavior; object-level authorization across tenants or users
- rate-limit behavior and
Retry-After; backward compatibility for supported old versions
Snapshot tests are useful if reviewed carefully; blind snapshot approval just institutionalizes mistakes faster.
Observability starts with correlation
Every request should carry or receive a request ID. Include it in logs, error responses, and downstream service calls. Structure logs so they can be queried:
{"level": "error", "requestId": "req_01J8ZJ1G1QYA4T5N4R8M4H6A7V",
"route": "GET /v1/invoices/{invoice}", "status": 500, "durationMs": 183,
"tenant": "ten_82kx", "error": "database timeout"}Log metadata, not payloads full of tokens, personal data, or card numbers. A useful log line should help you reconstruct behavior without becoming a second data breach.
Metrics need dimensions that match operations
Track request count, latency, error rate, and dependency latency by route template — not raw URL. /v1/invoices/inv_9c8b7a and /v1/invoices/inv_12345 are the same operation; aggregating by raw path destroys the signal and explodes cardinality.
The minimum dashboard for a mature API:
- p50/p95/p99 latency per route template; 4xx versus 5xx rates, separated
- auth failure and 403 rates; rate-limit rejections
- slow query count, queue depth, and usage by API version plus high-volume client
Test failure behavior before production does it
What happens when Redis is unavailable? When the database is read-only? When the auth provider latency jumps to ten seconds? Timeouts, retries, circuit breakers, and degraded responses are part of the API contract even if they never appear in the schema. Test them in staging or local fault-injection harnesses.
Field notes
- Never test only the happy path with factory-perfect data. Null optional fields and legacy rows are where serializers break.
- Do not retry non-idempotent POSTs automatically without idempotency keys.
- Alert on symptoms clients feel, such as elevated 5xx or p95 latency, not only host CPU.
- Add security regression tests for every authorization bug you fix; horizontal access bugs love to return.
Was this lesson helpful?