Contract testing helps make sure two parts of a system agree on how they talk to each other. It checks that the data sent and received matches what both sides expect.
0
0
Contract testing in Rest API
Introduction
When you have a frontend app talking to a backend API and want to avoid surprises.
When different teams build different services that need to work together smoothly.
Before releasing updates to an API to make sure clients won't break.
When you want to catch communication errors early without full end-to-end tests.
Syntax
Rest API
contract_test {
provider: "API Service",
consumer: "Frontend App",
interactions: [
{
request: {
method: "GET",
path: "/users/123"
},
response: {
status: 200,
body: {
id: 123,
name: "Alice"
}
}
}
]
}This is a simplified example of a contract test definition.
It describes what the consumer expects from the provider for a specific request.
Examples
This example shows a POST request contract where the consumer expects a new order ID in response.
Rest API
contract_test {
provider: "Order API",
consumer: "Mobile App",
interactions: [
{
request: { method: "POST", path: "/orders" },
response: { status: 201, body: { orderId: 789 } }
}
]
}This example shows a DELETE request contract where the consumer expects a 204 No Content response.
Rest API
contract_test {
provider: "User Service",
consumer: "Web Client",
interactions: [
{
request: { method: "DELETE", path: "/users/456" },
response: { status: 204 }
}
]
}Sample Program
This simple Python program tests if the API returns the expected user data for user 123. It checks the status code and required fields.
Rest API
import requests def test_get_user_contract(): url = "https://api.example.com/users/123" response = requests.get(url) assert response.status_code == 200 data = response.json() assert "id" in data and data["id"] == 123 assert "name" in data if __name__ == "__main__": test_get_user_contract() print("Contract test passed!")
OutputSuccess
Important Notes
Contract tests focus on the interface, not the internal logic of services.
They help catch mismatches early, saving time and bugs in production.
Use contract testing alongside other tests for best results.
Summary
Contract testing ensures two systems agree on data exchange.
It is useful when different teams or services communicate.
It helps catch errors early and keeps integrations stable.