I'm creating API docs with swagger and I can't find the way to represent an specific value in a response.
For example when there is a 404 error in the API, the response is like this:
{
"code": 404,
"result": "payment.notfound"
}
The value will always be 404, how can this be expressed in swagger.
Thanks!!
You can like this:
/paths:
/foo:
/get:
parameters: []
responses:
200:
description: it worked
404:
description: "it didn't work"
schema:
type: object
properties:
code:
type: integer
format: int32
result:
type: string
If you really want to say that result can only, ever be the string payment.notfound, you can simply set an enum:
result:
type: string
enum:
- "payment.notfound"
which means, "it's a string but can only be this value, ever".
Related
If we follow the OAS3 spec for Response here we can see that each response status code can have multiple media types and each media type in turn has a schema particular to it.
UseCase : For example oas3 example below, we can see 200 has a binary stream response but 400 has 3 media-types:application/json, application/xml, text/plain.
So is the client expected to request accept-type header with all the media-types mentioned below. How can we have specific media-type for 400 response code, or basically how we can convey to the REST Service to respond with media type as application/xml when its a 400 bad request and if 200 is returning a binary stream.
Does this OAS3 response multiple media-type make sense for Client/Server Errors. If yes then whats the accept-type set for expecting, say "application/xml" for 400 bad request.
Please refer the below swagger UI snap. Where we see a drop-down for the media-types for error code as well. But when we try out executing the rest operations, the accept header is only populated as per the 200 status code's media-type
openapi: 3.0.0
info:
version: "1.0"
title: Resource
description: Resource service
paths:
/resource:
get:
summary: getResource
description: getResource
operationId: get-resource
responses:
"200":
description: a binary document to be returned
content:
application/octet-stream:
schema:
type: string
format: binary
"400":
description: Bad Request
content:
application/json:
schema:
$ref: "#/components/schemas/Error400Element"
application/xml:
schema:
$ref: "#/components/schemas/Error400Element"
text/plain:
schema:
$ref: "#/components/schemas/Error400Element"
"500":
description: Internal Server Error
content:
application/json:
schema:
$ref: "#/components/schemas/Error500Element"
application/xml:
schema:
$ref: "#/components/schemas/Error500Element"
text/plain:
schema:
$ref: "#/components/schemas/Error500Element"
servers:
- url: http://localhost:8088/
components:
schemas:
Error400Element:
type: object
required:
- name
properties:
name:
type: string
number:
type: integer
Error500Element:
type: object
properties:
number:
type: integer
flag:
type: boolean
EDIT : modified the OAS3 spec and the SwaggerUI
I'm writing an OpenAPI spec for an existing API. This API returns status 200 for both success and failure, but with a different response structure.
For example, in the signup API, if the user signed up successfully, the API sends status 200 with the following JSON:
{
"result": true,
"token": RANDOM_STRING
}
And if there is a duplicated user, the API also sends status 200, but with the following JSON:
{
"result": false,
"errorCode": "00002", // this code is duplicated error
"errorMsg": "duplicated account already exist"
}
In this case, how to define the response?
This is possible in OpenAPI 3.0 but not in 2.0.
OpenAPI 3.0 supports oneOf for specifying alternate schemas for the response. You can also add multiple response examples, such as successful and failed responses. Swagger UI supports multiple examples since v. 3.23.0.
openapi: 3.0.0
...
paths:
/something:
get:
responses:
'200':
description: Result
content:
application/json:
schema:
oneOf:
- $ref: '#/components/schemas/ApiResultOk'
- $ref: '#/components/schemas/ApiResultError'
examples:
success:
summary: Example of a successful response
value:
result: true
token: abcde12345
error:
summary: Example of an error response
value:
result: false
errorCode: "00002"
errorMsg: "duplicated account already exist"
components:
schemas:
ApiResultOk:
type: object
properties:
result:
type: boolean
enum: [true]
token:
type: string
required:
- result
- token
ApiResultError:
type: object
properties:
result:
type: boolean
enum: [false]
errorCode:
type: string
example: "00002"
errorMsg:
type: string
example: "duplicated account already exist"
In OpenAPI/Swagger 2.0, you can only use a single schema per response code, so the most you can do is define the varying fields as optional and document their usage in the model description or operation description.
swagger: "2.0"
...
definitions:
ApiResult:
type: object
properties:
result:
type: boolean
token:
type: string
errorCode:
type: string
errorMsg:
type: string
required:
- result
I'm using Swagger Editor to document an existing API, built in Node, but it keeps giving me the following error:
Schema error at paths./upload/Rate.post.parameters[0]
is not exactly one from <#/definitions/parameter>,<#/definitions/jsonReference>
This error appears in 3 places of my code:
paths./upload/Rate.post.parameters[0]
paths./upload/Rate.post.parameters[1]
paths./users/register.post.parameters[0]
I've searched quite a bit, but, for example, this link did not solved my problem although it's the same error:
Swagger parameter error "is not exactly one from <#/definitions/parameter>"?
Here is my Swagger definition:
/users/register:
post:
tags:
- "users"
description: Allows an user to register at the Server
produces:
- application/json
parameters:
- name: body
in: body
description: JSON Object with information for a Register request from an User
schema:
type: object
required:
- username
- password
- weight
- height
- gender
- restRate
- age
properties:
username:
type: string
password:
type:
format: password
weight:
type: integer
height:
type: integer
gender:
type: string
restRate:
type: integer
age:
type: integer
# Expected responses for this operation:
responses:
# Response code
200:
description: Register successful
schema:
type: string
/upload/Rate:
post:
tags:
- "upload"
description: Allows an user to upload a file into the server
produces:
- application/json
consumes:
- multipart/form-data
parameters:
- name: body
in: formData
description: JSON Object with information for an upload request from an User
required: false
schema:
type: object
required:
- user
- overlap
- window
- latitude
- longitude
- time
- date
properties:
user:
type: string
overlap:
type: string
window:
type: string
latitude:
type: string
longitude:
type: string
time:
type: string
date:
type: string
- name: files
in: formData
description: File with the corresponding Rate
required: false
schema:
type: object
required:
- rate
properties:
rate:
type: file
# Expected responses for this operation:
responses:
# Response code
200:
description: Login successful
schema:
type: string
Maybe this will help, but the post route (upload/Rate) should receive a request that will be something like this, once I've parsed its parameters:
user = req.body.user;
rr = req.files.rate;
overlap = req.body.overlap;
windowT = req.body.window;
latitude = req.body.latitude;
longitude = req.body.longitude;
time = req.body.time;
date = req.body.date;
Thank you for your help and time!
There are multiple issues.
/upload/register:
Schema property password is missing the value for type.
Property name mismatch - restHR (under properties) vs restRate (in the required list).
upload/Rate:
The problem here is caused by object parameters in a multipart/form-data request. In OpenAPI (fka Swagger) 2.0, form parameters can be primitive values and arrays, but not objects. So your example cannot be described using OpenAPI 2.0.
If you were designing a new API (or if you could and were willing to change the API implementation to be compatible with OpenAPI 2.0), possible solutions would be:
Change the operation to consume application/json and combine all input parameters into a single JSON object. The file parameter would need to be implemented as a base64 string - type: string with format: byte.
Use multipart/form-data but split object parameters into individual form parameters.
The upcoming OpenAPI 3.0 will support object parameters in form data:
https://github.com/OAI/OpenAPI-Specification/blob/OpenAPI.next/versions/3.0.md#special-considerations-for-multipart-content
is it possible to have an array of complex object inside the get parameters?
If I try this code, I get a parameter definition error due to this line: $refs: '#/definitions/pax'
swagger: '2.0'
info:
version: 0.0.0
title: Simple API
paths:
/:
get:
parameters:
- name: passengers
in: query
type: array
items:
$refs: '#/definitions/pax'
responses:
200:
description: TODO
definitions:
pax:
type: object
properties:
name:
type: string
familyname:
type: string
For request parameters, only body parameter can be defined with an Object (model).
You will need to provide an example of the URL query string so that we can help you define it with Swagger/OpenAPI spec.
I have a GET route where I would like to encode an object parameter in the url as a query string.
When writing the swagger documentation I basically get errors that disallow me to use schema/object types in a query type parameter:
paths:
/mypath/:
get:
parameters
- in: path
name: someParam
description: some param that works
required: true
type: string
format: timeuuid #good param, works well
- $ref: "#/parameters/mySortingParam" #this yields an error
parameters:
mySortingParam
name: paging
in: query
description: Holds various paging attributes
required: false
schema:
type: object
properties:
pageSize:
type: number
cursor:
type: object
properties:
after:
type: string
format: string
The request query param having an object value would be encoded in an actual request.
Even though swagger shows an error at the top of the screen the object is rendered correctly in the swagger UI editor, however with that error floating on top of the documentation.
I don't think you can use "object" as query parameter in Swagger spec as query parameter only supports primitive type (https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types)
This is now possible with OpenAPI 3.0.
parameters:
- in: query
name: values
schema:
type: object
properties:
genre_id:
type: integer
author_id:
type: integer
title:
type: string
example:
{
"genre_id": 1,
"author_id": 1
}
style: form
explode: true
Here you can use style and explode keywords to specify how parameters should be serialised.
style defines how multiple values are delimited. Possible styles depend on the parameter location – path, query, header or cookie.
explode (true/false) specifies whether arrays and objects should
generate separate parameters for each array item or object property.
For the above example the url will be:
https://ebookstore.build/v1/users/books/search?genre_id=1&author_id=1
For more information on describing parameters with OpenAPI v3 and parameter serialisation, please refer here.
This is possible, just not with OpenAPI 2.0. OpenAPI 3.0 describes how this is possible here:
https://swagger.io/docs/specification/describing-parameters/
parameters:
- in: query
name: filter
# Wrap 'schema' into 'content.<media-type>'
content:
application/json: # <---- media type indicates how to serialize / deserialize the parameter content
schema:
type: object
properties:
type:
type: string
color:
type: string
In the meantime you could just have the query parameter as a plain old string type and then perform the serialization manually, then set the query parameter as required. This is what I'm doing until Swagger UI fully supports OpenAPI 3.0.