swagger:response
Usage
What it does
Declares a Go struct as a named response object.
It is emitted into the spec’s top-level responses map. Routes /
operations reference it by name via the response sub-language (Responses:
body in swagger:route, or the YAML $ref form in swagger:operation).
The struct’s fields contribute the response shape:
- A field named
Body(or carryingin: body) becomes the response body schema. The body may be a struct, a$ref’d model, or a primitive —Body stringemitsschema: {type: string}. - Other fields default to response headers: a field with neither
Body/in: bodynorin: headeris treated as a header, not a body property. A header’s key comes from thejson:tag / Go field name, or aname:keyword (e.g.name: X-Rate-Limit) — the canonical, preferred form, see thenamekeyword. - An anonymously embedded struct marked
in: bodyis the body (a$refto the model), not a promotion of its fields. - An
interface{}/any-typed field emits an empty schema ({}, or{type: array, items: {}}for a slice) — “any type”, valid OpenAPI 2.0.
Where it goes
On a struct declaration.
Grammar (EBNF)
The optional IDENT_NAME is the published response name (default: the
Go type’s name). A * wildcard (swagger:response *) explicitly marks
the response as a shared one, registered at #/responses/{name} for
operations to $ref by name — see
Sharing parameters & responses.
The annotation opens a SchemaBlock
body.
Supported keywords
- Body field: schema-context keywords.
- Header field: header-context keywords — numeric / length / format
validations,
pattern,enum,default,example,collectionFormat.required:is silently dropped (the OAS v2 Header object has norequiredfield).
Example
// PetsResponse is the list returned by listPets.
//
// swagger:response petsResponse
type PetsResponse struct {
// in: body
Body []Pet
}
// ErrorResponse is the default error payload.
//
// swagger:response errorResponse
type ErrorResponse struct {
// in: body
Body struct {
// Message is a human-readable error message.
Message string `json:"message"`
}
}Full source: docs/examples/concepts/routes/routes.go
{
"description": "PetsResponse is the list returned by listPets.",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/Pet"
}
}
}
Full source: docs/examples/concepts/routes/testdata/response.json
Routes can then reference it via response:genericError in their
Responses: body.
Full example. fixtures/enhancements/routes-full-petstore-shape/handlers.go.