API contract tests check published request and response behavior so clients survive deployments.
What It Does
API contract tests check published request and response behavior so clients survive deployments. The following examples distinguish a normal use case, a boundary case and a practical application.
Requirements and Compatibility
A local Composer project with a compatible PHPUnit version and isolated fixtures or stubs.
The code focuses on the core concept. Production implementation may also need routes, validation, persistence, authorization or deployment tooling.
Example 1: Basic Behavior
Check field presence and types at the response boundary.
<?php
$schema = ["id" => "int", "name" => "string"];
$response = ["id" => 12, "name" => "Lamp"];
foreach ($schema as $key => $type) { if (get_debug_type($response[$key] ?? null) !== $type) throw new UnexpectedValueException($key); }
echo "Contract satisfied";
Example 2: Another Case
A contract test catches incompatible response headers, not just JSON fields.
<?php
$expected = ["status" => 200, "content_type" => "application/json"];
$actual = ["status" => 200, "content_type" => "text/html"];
var_dump($expected === $actual);
Practical Example: Putting It to Use
Detect removed or renamed contract fields before shipping a client.
<?php
$required = ["id", "updated_at"];
$payload = ["id" => 4];
$missing = array_diff($required, array_keys($payload));
echo implode(", ", $missing);
Important Behavior and Edge Cases
A passing unit test cannot guarantee headers, status codes or serialization remain compatible.
Comparison with Related Functions or Approaches
| Option | What it means in practice |
|---|---|
| Writing Contract Tests for APIs | API contract tests check published request and response behavior so clients survive deployments. |
| Related approach | Combine provider contracts with consumer integration tests. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the important boundary for Writing Contract Tests for APIs | A passing unit test cannot guarantee headers, status codes or serialization remain compatible. |
| Assuming a related mechanism has the same behavior | Combine provider contracts with consumer integration tests. |
Key Takeaways
- API contract tests check published request and response behavior so clients survive deployments.
- A passing unit test cannot guarantee headers, status codes or serialization remain compatible.
- Combine provider contracts with consumer integration tests.
Before adapting these examples, verify the return values, test the failure paths and confirm that your application meets its security and environment requirements.