Multiple error codes using the same schema in Swagger UI - swagger-ui

I have a schema for a certain status code that i wan to use in multiple responses.
We can have multiple error messages for the same status code and may be distinct on each response.
ErrorCode:
type: object
properties:
error_code:
type: integer
description: error code
message:
type: string
example: No Authorization
description:
type: string
example: "You aren't allowed"
I would like to provide multiple examples for each response.
For example:
examples:
1:
error_code: 1
message: random 1
description: description 1
2:
error_code: 2
message: random msg 2
description: description 2

Related

How to provide separate examples for each HTTP status code?

I run into problem while trying to instruct Dredd to issue a different requests to trigger two distinct scenarios: success with code 201 and failure with code 400.
I tried to setup a separate example per HTTP status code but couldn't manage to do that.
I can add example section in requestBody but then it will be used in both example - for success and failure.
openapi: 3.0.2
info:
description: Body example per HTTP code illustration
version: 1.0.0
title: Profile
tags:
- name: profile
description: User profiles
paths:
/profiles:
post:
tags:
- profiles
summary: Create profile
operationId: createProfile
requestBody:
description: Create Profile
content:
application/json:
schema:
$ref: '#/components/schemas/CreateProfile'
required: true
responses:
'201':
description: Successful operation
headers:
Location:
schema:
type: string
description: Profile location
'400':
description: Profile is invalid (missing fields/null values)
content:
application/json:
schema:
$ref: '#/components/schemas/ProfileCreationError'
examples:
failing_scenrio:
summary: An example tailored to work with Dredd
value:
name: can't be blank
email: can't be blank
components:
schemas:
CreateProfile:
type: object
required:
- name
- email
- age
properties:
name:
type: string
email:
type: string
age:
type: integer
format: int32
minimum: 0
ProfileCreationError:
type: object
properties:
name:
type: string
email:
type: string
age:
type: integer
I would like to be able to run tests for both HTTP codes: 201 and 400. Bonus points for an example of how to do same thing with path param. For example, to provide both found and not found examples for /profiles/{id} (i.e. 200 and 404).
The OpenAPI 3 support is currently (July 2019, Dredd v11.2.9) experimental and this particular behavior is still undefined. The problem is tracked as a GitHub issue #1257. I recommend you to subscribe to the issue to see when it gets resolved or consider contributing a solution.

What does the "bad indentation of mapping entry" error mean in Swagger Editor?

I'm getting the "bad indentation of mapping entry" error in the Swagger Editor for the OpenAPI definition below. Can anyone tell what's wrong with the code below?
responses:
'200':
description: List all applicable errors for API
headers:
x-request-received-at:
type: string
description: A datetime stamp of when the request was received
x-response-sent-at:
type: string
description: A datetime stamp of when the response was sent
schema:
$ref: '#/definitions/ErrorResponse'
default:
description: An unexpected error occurred
schema:
$ref: '#/definitions/Error'
'/funeral/{contractReference}/agreement':
get:
summary: Get the funeral policy and debit order mandate agreement for the client to sign
operationId:
- get801FuneralCoverPlanAgreementHtml
- getAUTHORITYANDMANDATEFORPAYMENTINSTRUCTIONSHTML
tags:
- "FuneralCoverService"
- "InternalAPI"
parameters:
- name: contractReference
in: "path"
required: true
type: string
description: "Unique contract reference linked to the quote and estimate prepared for the client which should be used as input to the agreements."
maxLength: 80
Parameter attributes are misaligned. All attributes must have the same indentation level.
Wrong:
parameters:
- name: contractReference
in: "path"
required: true
type: string
description: "Unique contract reference linked to the quote and estimate prepared for the client which should be used as input to the agreements."
maxLength: 80
Correct:
parameters:
- name: contractReference
in: "path"
required: true
type: string
description: "Unique contract reference linked to the quote and estimate prepared for the client which should be used as input to the agreements."
maxLength: 80

How to define different responses for same HTTP status code in OpenAPI (Swagger)?

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

Semantic error at paths./findfood/{foodItemId} in Swagger Editor

I'm new to Swagger. I've written the following code using Swagger Editor, but I'm getting multiple errors. I've already looked at documentation and other examples, but I'm not able to clarify the problem.
swagger: '2.0'
info:
version: "1"
title: 'Grocery Shop'
description: 'This contains the url to access all the Grocery food related information. You can also add, update or delete any food item as well based on their respective id.'
contact:
email: you#your-company.com
tags:
- name: FoodItem
description: Specifically for Food item
- name: Category
description: Specifically for the category purpose
schemes:
- https
paths:
'/findfood/{foodItemId}':
get:
tags:
- FoodItem
summary: "Find the required food"
description: "Find the food with passed food id as an argument. Make sure that passed id exist otherwise it will return an error"
operationId: findFoodWithId
produces:
- "application/json"
parameters:
- in: path
name: foodItemId
required: true
type: integer
miniumum: 1
description: The id associated with the food in the grocery shop
responses:
200:
description: "successful operation"
schema:
$ref: '#definitions/Food'
404:
description: "Food is not found
definitions:
Food:
type: "object"
properties:
foodItemId:
type: integer
format: int32
required:
- foodItemId
xml:
name: "User"
# Added by API Auto Mocking Plugin
host: "localhost:8080"
basePath: "/grocery"
The errors which I'm getting are:
Semantic error at paths./findfood/{foodItemId} Declared path parameter
"foodItemId" needs to be defined as a path parameter at either the
path or operation level Jump to line 18
Schema error at paths./findfood/{foodItemId}.get.parameters[0] is not
exactly one from
<#/definitions/parameter>,<#/definitions/jsonReference> Jump to line
28
Parser error can not read a block mapping entry; a multiline key may
not be an implicit key Jump to line 48
These errors are misleading. The actual errors are:
miniumum: 1 contains a typo - miniumum
$ref: '#definitions/Food' needs a / between # and definitions: '#/definitions/Food'
description: "Food is not found needs the ending quotation mark.

Swagger: How to get formatted example json

I'm really struggling to understand the format of the examples section of a response. I have the following response defined for a 500 Internal Sever error.
500InternalServerError:
description: The server encountered an unexpected condition which prevented it from fulfilling the request
schema:
allOf:
- $ref: '#/definitions/Failure'
headers:
X-Rate-Limit-Limit:
description: The number of allowed requests in the current period
type: integer
X-Rate-Limit-Remaining:
description: The number of remaining requests in the current period
type: integer
X-Rate-Limit-Reset:
description: The number of seconds left in the current period
type: integer
examples:
application/json:
code: -1
message: The server encountered an unexpected condition which prevented it from fulfilling the request
When I load it up in swagger-ui, it looks like this:
How do I get the response to be formatted over multiple lines and look like this?:
{
"code": "-1",
"message": "The server encountered an unexpected condition which prevented it from fulfilling the request"
}
The lack of pretty print in the response-level examples seems to be a bug or missing functionality in Swagger UI 3.0.x. Feel free to submit an issue on GitHub.
The workaround is to use a schema-level example instead:
definitions:
Failure:
type: object
...
example:
code: "-1" # Quotes force the number to be treated as a string
message: The server encountered an unexpected condition which prevented it from fulfilling the request
By the way, you do not need allOf when using $ref alone (without combining it with other items):
schema:
$ref: '#/definitions/Failure'

Resources