Card 06/ 10
OpenAPI: A Contract Machines Can Read
An OpenAPI document describes each operation so tools can check requests, generate clients and draw documentation.
OpenAPI is a standard format, written in YAML or JSON, for describing an HTTP API: each path, its methods, their parameters, request bodies and responses, and the schemas of the data, using JSON Schema. Because the description is machine readable, tools can validate requests against it, generate client libraries, run tests and render documentation from the same file.
paths:
/orders:
post:
operationId: createOrder
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [sku, quantity]
properties:
sku: { type: string }
quantity: { type: integer, minimum: 1, maximum: 99 }
note: { type: string }
responses:
"201":
description: The order was created
"422":
description: A value broke a ruleReading the operation. The path is /orders and the method post. The request body is JSON and is required. Its schema says the body is an object, that sku and quantity must be present, that quantity is an integer from 1 to 99, and that note is an optional string. The responses list each status code the operation may return.
What a valid body looks like. {"sku": "A-1", "quantity": 2} is valid. {"sku": "A-1", "note": "gift"} is not, because quantity is required and an optional field does not make up for it. {"sku": "A-1", "quantity": 0} is not, because 0 is below the minimum.
What tools do with it. A gateway or middleware can reject invalid requests before they reach the code. Generators produce typed clients in many languages. Documentation tools render a page per operation with examples. Test tools check that real responses match the schemas.
Reuse. Schemas can be named once under components and referenced from many operations, so an Order is described in one place.
So write the contract as OpenAPI, and let tools enforce what people would otherwise check by hand.
← → move through sections and cards