0
0
Rest APIprogramming~5 mins

Why testing validates contracts in Rest API

Choose your learning style9 modes available
Introduction

Testing makes sure that different parts of a program agree on how to talk to each other. This agreement is called a contract.

When you want to check if your API sends and receives data correctly.
When you need to make sure your app works well with other apps or services.
When you want to avoid bugs caused by misunderstandings between parts of a system.
When you update your API and want to confirm old clients still work.
When you want to build trust that your service behaves as promised.
Syntax
Rest API
Test API endpoints by sending requests and checking responses.

Example:
GET /users/123
Expect status 200 and JSON with user info
Testing checks if the API follows the contract about request and response formats.
Contracts include rules like required fields, data types, and response codes.
Examples
This test checks if the product API returns the right data for product 45.
Rest API
GET /products/45
Expect status 200
Expect JSON with keys: id, name, price
This test checks if login works and returns a token as promised.
Rest API
POST /login
Send JSON {"username": "user", "password": "pass"}
Expect status 200
Expect JSON with token
This test checks if the API correctly handles requests for missing orders.
Rest API
GET /orders/999
Expect status 404
Expect JSON with error message
Sample Program

This program sends a request to get user 123. It checks if the response status is 200 and if the JSON has the expected keys. This confirms the API follows the contract.

Rest API
import requests

# Test to check if user API follows contract
response = requests.get('https://api.example.com/users/123')

if response.status_code == 200:
    data = response.json()
    if 'id' in data and 'name' in data and 'email' in data:
        print('Test passed: Contract is valid')
    else:
        print('Test failed: Missing keys in response')
else:
    print(f'Test failed: Unexpected status {response.status_code}')
OutputSuccess
Important Notes

Always test both success and error responses to fully validate the contract.

Automate these tests to run whenever you change your API.

Clear error messages help find contract problems quickly.

Summary

Testing checks if APIs follow agreed rules called contracts.

It helps catch mistakes early and keeps systems working together.

Good tests cover all expected responses and data formats.