Validating a response against an OpenAPI spec
Implement `validate_response(spec, operation_id, status_code, payload)`.
The function checks a JSON API response against an OpenAPI document and raises
`ContractError` when the contract is broken. It returns `None` when the response
is valid.
Supported OpenAPI 3 subset:
- the operation is found by `operationId` among `spec["paths"][*][method]`;
- the response is taken by exact code from `responses` (`"200"`, `"404"`);
- `$ref` is resolved inside the document only: `#/components/schemas/...`,
`#/components/responses/...`;
- if the response has no `content` or no `application/json`, the body is not
checked — return `None`;
- types: `object`, `array`, `string`, `integer`, `number`, `boolean`, `null`;
- `integer` rejects `bool` and `3.0`; `number` rejects `bool`;
- `required` is checked for objects;
- `properties` are validated recursively, extra fields are allowed;
- `items` is checked for arrays;
- `enum` and `nullable: true` are supported;
- the error carries the path to the field, for example `$.customer.name` or
`$.items[0].qty`.
Boundaries:
- unknown `operationId` — `ContractError`;
- undocumented status code — `ContractError`;
- broken or unknown schema — `ContractError`, not `KeyError` and not
`TypeError`;
- a `payload` of `None` is allowed only with `nullable: true` or for a response
without a JSON body.
The AI mentor is available after you log in: it sees your attempt history and does not spend resources on anonymous requests.
Log in and askHint 1
Which contract checks cannot be skipped if the test has to catch both a removed
field and `true` where a number is expected?