0
0
Rest APIprogramming~15 mins

Why testing validates contracts in Rest API - See It in Action

Choose your learning style9 modes available
Why Testing Validates Contracts in REST APIs
📖 Scenario: You are working on a simple REST API that provides user information. The API contract specifies that when you request a user by ID, you get a JSON response with id, name, and email. Testing helps ensure the API follows this contract exactly.
🎯 Goal: Build a simple test that checks if the API response matches the expected contract. This shows how testing validates that the API behaves as promised.
📋 What You'll Learn
Create a sample API response dictionary with user data
Define the expected contract keys in a list
Write a test that checks if all contract keys exist in the response
Print the test result as 'Contract Validated' or 'Contract Failed'
💡 Why This Matters
🌍 Real World
APIs must follow contracts so different programs can work together without errors. Testing these contracts prevents bugs and confusion.
💼 Career
Many software jobs require writing tests to verify APIs meet their contracts, ensuring reliable communication between services.
Progress0 / 4 steps
1
Create the sample API response data
Create a dictionary called api_response with these exact entries: 'id': 101, 'name': 'Alice', 'email': 'alice@example.com', and 'age': 30.
Rest API
Need a hint?

Use curly braces {} to create a dictionary with the exact keys and values.

2
Define the expected contract keys
Create a list called contract_keys with these exact strings: 'id', 'name', and 'email'.
Rest API
Need a hint?

Use square brackets [] to create a list with the exact strings.

3
Write the test to check the contract
Write a for loop using key to iterate over contract_keys. Inside the loop, check if key is not in api_response. If missing, set a variable valid to False and break the loop. Before the loop, set valid to True.
Rest API
Need a hint?

Start with valid = True. Use a for loop and if to check keys. Use break to stop if a key is missing.

4
Print the test result
Write a print statement that prints 'Contract Validated' if valid is True, otherwise prints 'Contract Failed'.
Rest API
Need a hint?

Use a single print with a conditional expression to show the result.