पाठ 6 / 25
Request Bodies, Responses and Status Codes
Describe request bodies, responses, media types, headers and examples.
What goes in and what comes out
A requestBody describes the payload of operations such as POST, PUT and PATCH: required, a description, and content, a map of media types (application/json, multipart/form-data, application/x-www-form-urlencoded) to a schema and optional examples. responses map HTTP status codes (as quoted strings, such as '200', '201', '404') or ranges ('4XX') and an optional default to response objects, each with a mandatory description, optional content and headers (for example Location for a created resource, Retry-After for 429, or rate-limit headers). Document every status code a client should handle, not just success: validation errors (400 or 422), authentication (401), authorisation (403), not found (404), conflicts (409), rate limiting (429) and server errors. Provide realistic examples (named examples with summaries) for requests and responses: documentation renders them, and mock servers use them. Use components/requestBodies and components/responses to avoid repeating the same definitions.
A create operation with body, headers and examples
201 with a Location header, and documented error responses.
post:
operationId: createOrder
parameters:
- $ref: '#/components/parameters/IdempotencyKey'
requestBody:
required: true
content:
application/json:
schema: { $ref: '#/components/schemas/NewOrder' }
examples:
twoItems:
summary: Two items, standard delivery
value:
customerId: cus_8Hd3kP0aQw1Z
items:
- { sku: BOOK-1984, quantity: 1 }
- { sku: PEN-BLUE, quantity: 3 }
delivery: STANDARD
responses:
'201':
description: Order created
headers:
Location:
description: URL of the new order
schema: { type: string, format: uri }
content:
application/json:
schema: { $ref: '#/components/schemas/Order' }
'409':
description: Same Idempotency-Key reused with a different body
content:
application/problem+json:
schema: { $ref: '#/components/schemas/Problem' }
'422': { $ref: '#/components/responses/ValidationProblem' }
'429': { $ref: '#/components/responses/TooManyRequests' }Every response needs a description
The description field is required on response objects, even when it seems obvious. Validators reject documents without it, and clear descriptions such as "Order created" help readers scanning the docs.
त्वरित जाँच: How are status codes written as keys in an OpenAPI responses object?
- As strings such as '200' or ranges such as '4XX', plus an optional default
- As unquoted numbers only
- As HTTP reason phrases
- They are not part of responses
Answer
As strings such as '200' or ranges such as '4XX', plus an optional default — Response keys are status code strings, ranges like 4XX, or default.