API Contracts: OpenAPI, Types, and Operation Boundaries
Lesson 1. A contract describes expected behavior
An API contract connects route, method, parameters, body, responses, and authentication requirements. OpenAPI provides a machine-readable model, but a published specification does not demonstrate server conformance. Compare actual routes, application version, and control requests. Record undocumented operations separately: omission from a document is not server-side denial.
For POST /orders, examine required product and quantity, quantity type and range, unknown-field handling, and permitted state changes. Use training objects with an explicit cleanup plan. Unlike reading, repeating creation can generate a second order. No live shop is provided here. The local body-validation model must not be described as an integration test result.
Lesson 2. A worked type boundary
# Educational excerpt, not a complete OpenAPI document
path: /orders
method: POST
required: [product, quantity]
properties:
product: {type: string}
quantity: {type: integer, minimum: 1, maximum: 10}
additionalProperties: false
JSON string “2” and number 2 differ. If the backend coerces strings, document that choice; otherwise client and server expectations diverge. An unknown role field must be rejected or safely ignored according to the contract. Supplying that field does not alone establish role modification; inspect persisted state.
A complete OpenAPI document contains additional required elements and references. This excerpt is a reduced operation record, not an importable specification. Preserve the original document separately from local annotations so analyst comments are not confused with developer requirements.
Lesson 3. Execute a local contract model
Save the following as contract_check.py and run python3 contract_check.py. Python 3 and its standard library suffice; there is no network or database. The fixture intentionally covers a small subset of JSON Schema and cannot replace a pipeline’s full OpenAPI validator.
# contract_check.py: offline training validator, not a full OpenAPI validator
import json
contract = {
'route': '/orders', 'method': 'POST',
'required': ['product', 'quantity'],
'properties': {'product': 'string', 'quantity': 'integer'},
'additionalProperties': False,
'quantityMinimum': 1,
'quantityMaximum': 10,
}
cases = [
('normal', {'product': 'Tea', 'quantity': 2}, []),
('missing', {'product': 'Tea'}, ['missing:quantity']),
('type', {'product': 'Tea', 'quantity': '2'}, ['type:quantity']),
('unknown', {'product': 'Tea', 'quantity': 2, 'role': 'admin'}, ['unknown:role']),
('range', {'product': 'Tea', 'quantity': 0}, ['range:quantity']),
]
def validate(body):
errors = []
for key in contract['required']:
if key not in body:
errors.append('missing:' + key)
for key, value in body.items():
expected = contract['properties'].get(key)
if expected is None:
errors.append('unknown:' + key)
elif expected == 'string' and not isinstance(value, str):
errors.append('type:' + key)
elif expected == 'integer' and type(value) is not int:
errors.append('type:' + key)
elif key == 'quantity' and not 1 <= value <= 10:
errors.append('range:' + key)
return errors
for name, body, expected in cases:
actual = validate(body)
assert actual == expected, (name, actual)
print(name, actual or 'ACCEPTED')
print('contract controls passed:', len(cases))
Expect ACCEPTED for normal and the specified single error for each other case. Using type(value) is int excludes bool: Python booleans inherit from integers, whereas this training contract requires an actual JSON integer. Error ordering is deterministic for these inputs; production clients should not depend on incidental defect-list ordering.
Lesson 4. Tools and evidence quality
Swagger UI and similar viewers help inspect approved specifications. Burp or an HTTP client records actual requests. Schemathesis can generate schema-driven checks, but requires approved actions, limits, and fixture state. A generator does not automatically know the business rule for order ownership. Nuclei likewise does not replace authorization-contract testing.
For Russian on-prem APIs, clarify where documentation may be stored and exported. Specifications can reveal internal names and data models; do not upload them to a third-party service without owner permission. OpenAPI is not FSTEC certification or proof of lawful information processing. Applicable obligations require a separate determination.
Practice. Extend coverage while preserving controls
Add quantity=10, quantity=11, quantity=true, empty product, and a body missing both required fields. The first three have defined model outcomes. For an empty string, request an additional business requirement because no minLength exists. Expect acceptance of 10, rejection of 11 and bool, and current acceptance of an empty product string.
Build a matrix linking requirement, test, expected outcome, observation, and source. Keep local model behavior distinct from a real backend. Temporarily remove the range check in a copy; the range test must fail. Restore it afterward. Acceptance requires runnable original and extended controls, no invented business requirement, and conclusions limited to the fixture. Deliver an operation contract and reproducible checks suitable for developer discussion. Include missing content-type, request-size, and duplicate-field policies as separate questions rather than implying this small validator already covers them.
References
OpenAPI: specification JSON Schema: object validation Schemathesis: documentation
Account identity and access rights
Change the conditions and observe this training model. It runs in your browser and does not change your computer.
Choose conditions above to see an explanation of the result.
Independent exercise · Russian

Осенью 2026 года диспетчеры казанского распределительного центра переходят на бронирование окон разгрузки через API. Интегратор описал продолжительность окна как число минут. Владелец склада согласовал только целые значения от 15 до 90 включительно. Перед выпуском нужно согласовать контракт и примеры в документации.
Evidence
Черновик OpenAPI задаёт для durationMinutes тип number, minimum 15, maximum 90. Поле отсутствует в списке required. В наборе примеров есть объект без durationMinutes и три объекта со значениями 22.5, «30» (строка) и 90. Остальные поля во всех четырёх записях считаются корректными.
Assignment
Сдайте исправленное описание поля и таблицу из четырёх строк. Для каждого примера отметьте, примет ли его исходная схема и каким должно стать решение после правки.
Compare your reasoning
Добавьте durationMinutes в required и укажите type integer с прежними границами. Исходная схема пропускает отсутствие поля, 22.5 и 90, исправленная пропускает только 90. Строка «30» не проходит обе схемы. Числа 15 и 90 включены в диапазон, округление дроби изменило бы смысл договора.
Personal practice environment
Check an excerpt, find matching lines and compute the SHA-256 of the original text. Temporary data expires after 30 minutes or when you close the environment.
Sign in