Skip to content

Commit 8450a86

Browse files
author
Oliver Kahrmann
committed
Add documentation for responses with multiple content types
1 parent 38ad250 commit 8450a86

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

README.md

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,70 @@ func NewStringID(v string) ID
153153
func NewIntID(v int) ID
154154
```
155155

156+
## Multiple Response Content Types
157+
158+
For responses with multiple possible content types, a parameter is automatically added to represent the HTTP Accept header.
159+
If desired, the generated server can use this parameter to pick a response format, and the generated client can use this parameter to set the Accept header.
160+
Existing parameters remain untouched, and if a parameter is explicitly defined for the Accept header, no automatic parameter is generated.
161+
162+
Given the following OpenAPI spec:
163+
164+
```yaml
165+
openapi: 3.0.3
166+
paths:
167+
/multipleContentTypes:
168+
get:
169+
operationId: multipleContentTypes
170+
responses:
171+
"200":
172+
description: "OK"
173+
content:
174+
application/octet-stream:
175+
schema:
176+
type: string
177+
format: binary
178+
application/json:
179+
schema:
180+
type: object
181+
properties:
182+
data:
183+
type: string
184+
required:
185+
- "data"
186+
```
187+
188+
The server can handle the Accept header like this:
189+
190+
```go
191+
func (h HandlerImplementation) MultipleContentTypesWithoutParameters(ctx context.Context, params api.MultipleContentTypesParams) (api.MultipleContentTypesRes, error) {
192+
if params.Accept.MatchesContentType(api.MediaTypeApplicationOctetStream) {
193+
return &api.MultipleContentTypesOKApplicationOctetStream{
194+
Data: bytes.NewBufferString("byte content"),
195+
}, nil
196+
} else if params.Accept.MatchesContentType(api.MediaTypeApplicationJSON) {
197+
return &api.MultipleContentTypesOKApplicationJSON{
198+
Data: "json data",
199+
}, nil
200+
} else {
201+
// Local error type which may be used in convenient errors to generate an appropriate response
202+
return nil, errNotAcceptable
203+
}
204+
}
205+
```
206+
207+
And the client can set it like this:
208+
209+
```go
210+
r, err := client.MultipleContentTypes(ctx, api.MultipleContentTypesParams{
211+
Accept: http.AcceptHeaderNew(api.MediaTypeApplicationOctetStream),
212+
})
213+
res, ok := r.(*api.MultipleContentTypesOKApplicationOctetStream)
214+
if !ok {
215+
// Wrong type
216+
}
217+
// Handle content
218+
```
219+
156220
## Extension properties
157221

158222
OpenAPI enables [Specification Extensions](https://spec.openapis.org/oas/v3.1.0#specification-extensions),

0 commit comments

Comments
 (0)