0
0
Rest APIprogramming~30 mins

Contract testing in Rest API - Mini Project: Build & Apply

Choose your learning style9 modes available
Contract Testing for a REST API
📖 Scenario: You are working on a simple REST API that provides information about books in a library. To make sure the API works as expected for other developers who use it, you will write contract tests. These tests check that the API responses match the agreed format and data types.
🎯 Goal: Build a contract test that verifies the API response for the /books endpoint matches the expected structure and data types.
📋 What You'll Learn
Create a sample API response data structure
Define the expected contract for the API response
Write a test that compares the actual response to the contract
Print the test result indicating if the contract is met
💡 Why This Matters
🌍 Real World
Contract testing helps ensure that APIs deliver data in the format and types that clients expect, preventing bugs and misunderstandings.
💼 Career
Many software development roles require writing or understanding API contract tests to maintain reliable and stable services.
Progress0 / 4 steps
1
Create sample API response data
Create a variable called api_response that holds a list of dictionaries. Each dictionary represents a book with these exact keys and values: {'id': 1, 'title': '1984', 'author': 'George Orwell'} and {'id': 2, 'title': 'To Kill a Mockingbird', 'author': 'Harper Lee'}.
Rest API
Need a hint?

Use a list with two dictionaries exactly as shown.

2
Define the expected contract
Create a variable called expected_contract that holds a dictionary with keys id, title, and author. The values should be the expected data types: int for id and str for title and author.
Rest API
Need a hint?

Use a dictionary with keys matching the book keys and values as the Python types.

3
Write the contract test logic
Write a function called check_contract that takes response and contract as parameters. It should return True if every item in response has all keys in contract with values of the correct type. Otherwise, return False. Use a for loop with variables item and check each key and type.
Rest API
Need a hint?

Use nested loops to check each key and type in each item.

4
Print the contract test result
Use print to display the result of calling check_contract with api_response and expected_contract. The output should be True if the contract is met.
Rest API
Need a hint?

Call the function and print its result.