Topics / 🌐 API & Software Architecture / 🧪 Level 91: API Architecture: Testing APIs

Python exercise · about 5 minutes · free

Contract Tests: Does the Response Match the Promise?

A field renamed from 'id' to 'user_id' passes every unit test and breaks every client. A contract check catches it.

A contract states what a response must contain: status, required fields and their types. A contract test checks a real or stubbed response against it, so provider and consumer drift is caught in CI without deploying everything. Extra fields are allowed (clients should ignore them); missing or wrongly-typed ones are violations.

Prices, versions and service names last checked 2026-11-19. They change, so confirm on the official pages before you rely on them.

Flow: response → check status and fields (missing or wrong type) → violations list (empty means it keeps the promise)responsecheck status and fieldsmissing or wrong typeviolations listempty means it keeps the promise
Your quest: Write check_contract(response, contract). response is {"status", "body"}; contract is {"status", "fields"} where fields maps name to type. Return a list of violation strings, in this order: "status: expected 200, got 404" (if different), then for each field sorted by name "missing: id" or "type: name expected str".
Try it now Runs in your browser. No sign-in needed. Ctrl+Enter to run.
HintStart with the status check, then loop <code>sorted(contract['fields'])</code> and compare with <code>isinstance</code>.
Output appears here.

Open it in the full course → Free with Google: saves your progress and unlocks 627 lessons.

In this level you'll learn:
More in Level 91: API Architecture: Testing APIs

Share on LinkedIn