Swagger описание ошибок

OAS 3 This guide is for OpenAPI 3.0. If you use OpenAPI 2.0, see our OpenAPI 2.0 guide.

An API specification needs to specify the responses for all API operations. Each operation must have at least one response defined, usually a successful response. A response is defined by its HTTP status code and the data returned in the response body and/or headers. Here is a minimal example:

paths:
  /ping:
    get:
      responses:
        '200':
          description: OK
          content:
            text/plain:
              schema:
                type: string
                example: pong

Response Media Types

An API can respond with various media types. JSON is the most common format for data exchange, but not the only one possible. To specify the response media types, use the content keyword at the operation level.

paths:
  /users:
    get:
      summary: Get all users
      responses:
        '200':
          description: A list of users
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ArrayOfUsers'
            application/xml:
              schema:
                $ref: '#/components/schemas/ArrayOfUsers'
            text/plain:
              schema:
                type: string

  # This operation returns image
  /logo:
    get:
      summary: Get the logo image
      responses:
        '200':
          description: Logo image in PNG format
          content:
            image/png:
              schema:
                type: string
                format: binary

More info: Media Types.

HTTP Status Codes

Under responses, each response definition starts with a status code, such as 200 or 404. An operation typically returns one successful status code and one or more error statuses. To define a range of response codes, you may use the following range definitions: 1XX, 2XX, 3XX, 4XX, and 5XX. If a response range is defined using an explicit code, the explicit code definition takes precedence over the range definition for that code. Each response status requires a description. For example, you can describe the conditions for error responses. Markdown (CommonMark) can be used for rich text representation.

      responses:
        '200':
          description: OK
        '400':
          description: Bad request. User ID must be an integer and larger than 0.
        '401':
          description: Authorization information is missing or invalid.
        '404':
          description: A user with the specified ID was not found.
        '5XX':
          description: Unexpected error.

Note that an API specification does not necessarily need to cover all possible HTTP response codes, since they may not be known in advance. However, it is expected to cover successful responses and any known errors. By “known errors” we mean, for example, a 404 Not Found response for an operation that returns a resource by ID, or a 400 Bad Request response in case of invalid operation parameters.

Response Body

The schema keyword is used to describe the response body. A schema can define:

  • an object or an array — typically used with JSON and XML APIs,
  • a primitive data type such as a number or string – used for plain text responses,
  • a file – (see below).

Schema can be defined inline in the operation:

      responses:
        '200':
          description: A User object
          content:
            application/json:
              schema:
                type: object
                properties:
                  id:
                    type: integer
                    description: The user ID.
                  username:
                    type: string
                    description: The user name.

or defined in the global components.schemas section and referenced via $ref. This is useful if multiple media types use the same schema.

      responses:
        '200':
          description: A User object
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
          description: The user ID.
        username:
          type: string
          description: The user name.

Response That Returns a File

An API operation can return a file, such as an image or PDF. OpenAPI 3.0 defines file input/output content as type: string with format: binary or format: base64. This is in contrast with OpenAPI 2.0, which uses type: file to describe file input/output content. If the response returns the file alone, you would typically use a binary string schema and specify the appropriate media type for the response content:

paths:
  /report:
    get:
      summary: Returns the report in the PDF format
      responses:
        '200':
          description: A PDF file
          content:
            application/pdf:
              schema:
                type: string
                format: binary

Files can also be embedded into, say, JSON or XML as a base64-encoded string. In this case, you would use something like:

paths:
  /users/me:
    get:
      summary: Returns user information
      responses:
        '200':
          description: A JSON object containing user name and avatar
          content:
            application/json:
              schema:
                type: object
                properties:
                  username:
                    type: string
                  avatar:          # <-- image embedded into JSON
                    type: string
                    format: byte
                    description: Base64-encoded contents of the avatar image

anyOf, oneOf

OpenAPI 3.0 also supports oneOf and anyOf, so you can specify alternate schemas for the response body.

      responses:
        '200':
          description: A JSON object containing pet information
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/Cat'
                  - $ref: '#/components/schemas/Dog'
                  - $ref: '#/components/schemas/Hamster'

Empty Response Body

Some responses, such as 204 No Content, have no body. To indicate the response body is empty, do not specify a content for the response:

      responses:
        '204':
          description: The resource was deleted successfully.

Responses from an API can include custom headers to provide additional information on the result of an API call. For example, a rate-limited API may provide the rate limit status via response headers as follows:

HTTP 1/1 200 OK
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 99
X-RateLimit-Reset: 2016-10-12T11:00:00Z

{ ... }

You can define custom headers for each response as follows:

paths:
  /ping:
    get:
      summary: Checks if the server is alive.
      responses:
        '200':
          description: OK
          headers:
            X-RateLimit-Limit:
              schema:
                type: integer
              description: Request limit per hour.
            X-RateLimit-Remaining:
              schema:
                type: integer
              description: The number of requests left for the time window.
            X-RateLimit-Reset:
              schema:
                type: string
                format: date-time
              description: The UTC date/time at which the current rate limit window resets.

Note that, currently, OpenAPI Specification does not permit to define common response headers for different response codes or different API operations. You need to define the headers for each response individually.

Default Response

Sometimes, an operation can return multiple errors with different HTTP status codes, but all of them have the same response structure:

      responses:
        '200':
          description: Success
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'

        # These two error responses have the same schema
        '400':
          description: Bad request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '404':
          description: Not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

You can use the default response to describe these errors collectively, not individually. “Default” means this response is used for all HTTP codes that are not covered individually for this operation.

      responses:
        '200':
          description: Success
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'

        # Definition of all error statuses
        default:
          description: Unexpected error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

Reusing Responses

If multiple operations return the same response (status code and data), you can define it in the responses section of the global components object and then reference that definition via $ref at the operation level. This is useful for error responses with the same status codes and response body.

paths:
  /users:
    get:
      summary: Gets a list of users.
      response:
        '200':
          description: OK
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ArrayOfUsers'
        '401':
          $ref: '#/components/responses/Unauthorized'   # <-----
  /users/{id}:
    get:
      summary: Gets a user by ID.
      response:
        '200':
          description: OK
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '401':
          $ref: '#/components/responses/Unauthorized'   # <-----
        '404':
          $ref: '#/components/responses/NotFound'       # <-----

# Descriptions of common components
components:
  responses:
    NotFound:
      description: The specified resource was not found
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    Unauthorized:
      description: Unauthorized
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'

  schemas:
    # Schema for error response body
    Error:
      type: object
      properties:
        code:
          type: string
        message:
          type: string
      required:
        - code
        - message

Note that responses defined in components.responses are not automatically applied to all operations. These are just definitions that can be referenced and reused by multiple operations.

Linking Response Values to Other Operations

Certain values in the response could be used as parameters to other operations. A typical example is the «create resource» operation that returns the ID of the created resource, and this ID can be used to get that resource, update or delete it. OpenAPI 3.0 provides the links keyword to describe such relationships between a response and other API calls. For more information, see Links.

FAQ

Can I have different responses based on a request parameter? Such as:

GET /something -> {200, schema_1}
GET /something?foo=bar -> {200, schema_2}

In OpenAPI 3.0, you can use oneOf to specify alternate schemas for the response and document possible dependencies verbally in the response description. However, there is no way to link specific schemas to certain parameter combinations.

Reference

Response Object

MediaType Object

Components Object

Did not find what you were looking for? Ask the community
Found a mistake? Let us know

Error Declaration

The API Declaration should describe how the different errorResponses map to the
business logic of the API. For instance, if a 404 is returned, it may be due to a variety
of reasons—invalid resource, object cannot be found, invalid parameter, etc. While
the HTTP response codes can be interpreted by the consumer correctly, often they are
ambiguous and can benefit from some documentation.

The errorResponse object contains just two fields, as shown below:

"errorResponses":[
  {
    "code": 400,
    "reason": "Raised if a user supplies an invalid username format"
  },
  {
    "code": 404,
    "reason": "The user cannot be found"
  }
],

code. This is the HTTP response code which causes the error condition

reason. This is a text explanation of what will cause the error condition

Imagine you are working under following circumstances:

  • You have REST API modules with API documentation generated into swagger-ui.html
  • Possible HTTP status codes for endpoints are documented well via io.swagger.annotations.* on controller method level for each endpoint.
  • In case of some error state (4XX or 5XX) application replies with ErrorResponseDTO with structure like

    "ErrorResponseDTO": {
      "type": "object",
      "properties": {
         "errorCode": {
           "type": "integer",
           "format": "int32"
         },
        "message": {
          "type": "string"
        }
      }
    }
    
  • Application have tens of errorCodes (within range like 1 — XX and please consider them as a legacy definiton without an easy way to change them).

  • List of errorCodes is relevant for the whole application so you prefer to keep their definiton list/table in overall API documentation rather then maintaining errorCodes definiton for each API endpoint separately.

Now you are looking for an effective way how to document these application error codes into API contract.

The approach of including a list of errorCodes with codes description into generated swagger-ui.html seems like a better way to keep API documentation up to date instead of having static and handwritten codes definition table attached in Markdown format in some Readme file.

Would you please have any recommendation how to document various codes which your applications produce?

Do you follow some specific good practice in this topic?

Thank you in advance.

asked Mar 14, 2019 at 15:43

Zbynek R's user avatar

Meanwhile within a small internal dev team and with frequent API extensions there can be used generated swagger-ui with included error codes:

  @Bean
  public Docket swaggerSettings() {
    ApiSelectorBuilder builder = new Docket(DocumentationType.SWAGGER_2)
      .apiInfo(
        new ApiInfoBuilder()
          .title("Response errorCodes table")
          .description(RestResponse.generateErrorsDocumentation().toString())
          .build()
      )
      ...
      .select();

    return builder.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
        .paths(PathSelectors.any())
        .build()
        .useDefaultResponseMessages(false);
  }

answered Nov 16, 2021 at 22:18

Zbynek R's user avatar

I have found the solutions to incorporate response code in Swagger Ui, which can be beneficial for those seeking a resolution. Solution 1 involves utilizing decorators to extend the functionality of the existing service code.

Documenting error codes definition in Swagger API contract


Solution:

In the midst of a small internal development team and frequent API extensions, one can utilize the generated

swagger-ui

which includes error codes.

  @Bean
  public Docket swaggerSettings() {
    ApiSelectorBuilder builder = new Docket(DocumentationType.SWAGGER_2)
      .apiInfo(
        new ApiInfoBuilder()
          .title("Response errorCodes table")
          .description(RestResponse.generateErrorsDocumentation().toString())
          .build()
      )
      ...
      .select();
    return builder.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
        .paths(PathSelectors.any())
        .build()
        .useDefaultResponseMessages(false);
  }

How to define Error schema using Spring Boot Open API 3?, You add the schema implementation of your ErrorDetails on the content attribute. For exampel: @ApiResponse(responseCode = «500», description

API Platform — How to add response code in Swagger UI using decorator to add 400, 404, 500 response code so client know the response in adwance


Solution 1:

When implementing decorators, you are essentially expanding upon the current service code by obtaining the path and subsequently configuring the custom operation within the swagger context using the provided code.

If you notice the code block:

$openApi->getPaths()->addPath('/api/grumpy_pizzas/{id}', $pathItem->withGet(
            $operation->withParameters(array_merge(
                $operation->getParameters(),
                [new Model\Parameter('fields', 'query', 'Fields to remove of the output')]
            ))
        ));

The PathItem in question accepts an Operation object as a parameter, which contains a method called

withResponses

. This method allows you to modify any responses generated by your path. It is recommended to refer to the source code in PathItem.php to find the best fit for your specific requirements.

Construct a response based on the Response object and include it in both the Operation and the path.

Utilizing an editor equipped with a reliable linter can enhance your coding experience by providing a comprehensive display of accessible methods.


Solution 2:

Although it is past the optimal time for posting, I have discovered the solutions to incorporate response codes into my Swagger UI. This information can be beneficial for individuals seeking a solution.

private function setErrorResponseDescriptions(OpenApi $openApi): OpenApi
{
    $schemas = $openApi->getComponents()->getSchemas();
    $schemas['Error'] = [
        'type'       => 'object',
        'properties' => [
            'type' => [
                'type'     => 'string',
                'readOnly' => true,
            ],
            'title' => [
                'type'     => 'string',
                'readOnly' => true,
            ],
            'detail' => [
                'type'     => 'string',
                'readOnly' => true,
            ],
        ],
    ];
    $schemas['ValidationError'] = [
        'type'       => 'object',
        'properties' => [
            'type' => [
                'type'     => 'string',
                'readOnly' => true,
            ],
            'title' => [
                'type'     => 'string',
                'readOnly' => true,
            ],
            'detail' => [
                'type'     => 'string',
                'readOnly' => true,
            ],
            'validations' => [
                'type'     => 'array',
                'readOnly' => true,
                'items'    => [
                    'type'       => 'object',
                    'properties' => [
                        'propertyPath' => [
                            'type'     => 'string',
                            'readOnly' => true,
                        ],
                        'message' => [
                            'type'     => 'string',
                            'readOnly' => true,
                        ],
                    ]
                ]
            ]
        ],
    ];
    foreach ($openApi->getPaths()->getPaths() as $path => $pathItem) {
        foreach (['PUT', 'POST', 'PATCH', 'GET'] as $method) {
            $item = $pathItem->{'get' . ucfirst($method)}();
            if ($item) {
                $item->addResponse(
                    new Model\Response(
                        description: 'Unauthorized',
                        content: new \ArrayObject([
                            'application/problem+json' => [
                                'schema' => [
                                    '$ref' => '#/components/schemas/Error',
                                ],
                            ],
                        ])
                    ),
                    '401'
                );
                if ('GET' !== $method) {
                    $item->addResponse(
                        new Model\Response(
                            description: 'Bad request',
                            content: new \ArrayObject([
                                'application/problem+json' => [
                                    'schema' => [
                                        '$ref' => '#/components/schemas/ValidationError',
                                    ],
                                ],
                            ])
                        ),
                        '400'
                    );
                } else {
                    $item->addResponse(
                        new Model\Response(
                            description: 'Not Found',
                            content: new \ArrayObject([
                                'application/problem+json' => [
                                    'schema' => [
                                        '$ref' => '#/components/schemas/Error',
                                    ],
                                ],
                            ])
                        ),
                        '404'
                    );
                }
            }
        }
    }
    return $openApi;
}

Getting 405 error in OpenAPI swagger page if I put only path, Try this annotation above controller method: @io.swagger.v3.oas.annotations.parameters.RequestBody(content = @Content). See Swagger UI not

How can I display error code description in sample code section?


Solution:

An approach to accomplish this is by defining a string using

@ApiResponse

as an illustration.

You can achieve this in two way

1. Create a class for defining the format of your error messages, or utilize any built-in formats available.

public class ExceptionResponse {
    private Instant time;
    private int status;
    private String error;
    private String exception;
    private String message;
}

Next, create your own personalized message string using the example provided.

public static final String exampleInternalError = "{\r\n" + "  \"status\": 500,\r\n" + "\"error\": Bad Request,\r\n"
            + "  \"message\": \"Your custome message goes here\"\r\n" + "}";

same is used to show the example as

@ApiResponse(responseCode = "400", description = "Bad Request", 
                  content = @Content(schema = @Schema(implementation = ExceptionResponse .class), 
                        examples = @ExampleObject(description = "Bad Request", value = exampleInternalError)))

The swagger will display the following:

2. If the above format is not preferred, an alternative option is to use it in a simpler manner.

as mentioned below

@ApiResponse(responseCode = "400", description = "Bad Request", 
content = @Content(schema = @Schema(implementation = String.class), 
              examples = @ExampleObject(description = "Bad Request", value = "\"Your details about error code and error message goes here")))

The following will be displayed on swagger:

Does response status code make sense for multiple media types for, 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

Response status is 500 for swagger appears once HttpGet for a specific object is implemented


Solution:

After closely examining the Debug Window, I discovered the solution with the help of those who encouraged me. Despite the absence of a conventional «error color» message, I found a hidden message indicating that the CS file I was referencing was ambiguous. To resolve this issue, I modified the code to specifically reference either «API.Models.Order» or «API.Projections.Order».

How to Map response error model in swagger 3.0.0?, () { return ; ResponseMessageBuilder().code(HttpServletResponse.SC_BAD_REQUEST) .message(HttpStatus.BAD_REQUEST.getReasonPhrase()) .responseModel

I’m wondering about good practices about including common error types in Swagger/OpenAPI definition.

Let’s consider following controller method:

[HttpGet]
[ProducesResponseType(StatusCodes.Status400BadRequest)] // to be or not to be?
public ActionResult SomeMethod(Foo foo)
{
    if (foo.Property != "expectedValue")
    {
        return BadRequest();
    }

    return Ok();
}

So, I’m performing some logic in the controller, which might end up in a state in which I want to return 400 BadRequest. Note, that I don’t return any content.
Since I develop a REST API that generates Swagger/OpenAPI definition and tools like autorest may be used to generate client code based on that definition, I want to be sure it is as accurate as possible.

My question is:

  • should I declare explicitly that the user might get 400 Bad Request

OR

  • this makes sense only in case I want to describe the format of response content (in case 400Bad request has some content)

The same applies to codes like 401, 404 etc.

asked Dec 20, 2021 at 19:29

Tomasz Madeyski's user avatar

Tomasz MadeyskiTomasz Madeyski

10.8k3 gold badges50 silver badges62 bronze badges

Even if (in addition to the returned http code, 400, 401, etc..) you do not return any payload at all, you should yet explicitly declare such responses.

Do not forget that in a «code-first» approach, your build chain could automatically generate the OpenApi contract (based on your code) as well as a nice user documentation.

In the contrary approach (contract-first), the code generated based on your OpenApi file would contain these response descriptions.

answered Dec 21, 2021 at 13:48

TacheDeChoco's user avatar

TacheDeChocoTacheDeChoco

3,6831 gold badge14 silver badges17 bronze badges

If you plan to use client code generation, then it’s always better to use these declarations, because code generators (like autorest or NSwag) can use this information (usually from a swagger definition aka swagger.json) to generate more correct responses and error handling procedures.
Here, for example, you can see what can happen if you omit such declarations.

Also, remember, that in API controllers you can use web API conventions.
It says that these conventions allow you to:

  • Define the most common return types and status codes returned from a specific type of action.
  • Identify actions that deviate from the defined standard.

So, generally speaking, they can help you to make your code more concise.

answered Dec 30, 2021 at 5:09

AndrewSilver's user avatar

AndrewSilverAndrewSilver

9862 gold badges14 silver badges25 bronze badges

answered Dec 20, 2021 at 20:04

S Shahar's user avatar

1

Понравилась статья? Поделить с друзьями:
  • Swot анализ ошибки
  • System pte misuse ошибка windows 10 при установке
  • System overflowexception ошибка переполнения
  • Swtor русификатор ошибка необрабатываемое исключение
  • System fault service now touareg ошибка