Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Response model for specific status codes using Swagger

I am using Swagger to document my REST API (using asp.net web api 2). Is there a way in swagger to give response models for each possible responses for a given api call? I am annotating the status code response using the xml comments like so:

    /// <summary>
    /// Save a person
    /// </summary>
    /// <response code="200">Ok</response>
    /// <response code="400">Bad Request</response>
    /// <response code="500">Internal Server error</response>
    public HttpResponseMessage SavePerson() {...}

enter image description here

like image 640
Kaladin Avatar asked Apr 07 '15 10:04

Kaladin


People also ask

What is model in Swagger?

A swagger:model annotation optionally gets a model name as extra data on the line. when this appears anywhere in a comment for a struct, then that struct becomes a schema in the definitions object of swagger. The struct gets analyzed and all the collected models are added to the tree.

What is operationId in Swagger?

operationId is an optional unique string used to identify an operation. If provided, these IDs must be unique among all operations described in your API. ... Some common use cases for operationId are: Some code generators use this value to name the corresponding methods in code.


3 Answers

You can try using cref="TYPE HERE" on your XML comments like this.

/// <response code="400" cref="CustomErrorModel">Bad Request</response>

B ut I would suggest using annotations that Swagger gives you.

[SwaggerResponse(HttpStatusCode.OK, Type = typeof(OnlineMerchantQueryResponseInformation))]

attribute your Controllers with this.

like image 151
EvilToaster101 Avatar answered Oct 13 '22 21:10

EvilToaster101


Your signature says you're returning a HttpResponseMessage, not a data model. If you're returning an IActionResult, and you're using ASP.NET Core, you can use the "ProducesResponseType" attribute:

[ProducesResponseType(typeof(IEnumerable<YourModel>), 200)]

ProducesResponsesType is in Microsoft.AspNetCore.Mvc namespace.

See https://github.com/domaindrivendev/Swashbuckle.AspNetCore#list-operation-responses "Explicit Responses"

like image 29
Elton Avatar answered Oct 13 '22 21:10

Elton


If you are using Swashbuckle, You can try

 [SwaggerResponse(200, typeof(CustomModel))]

and you additionally add a comment for that response type as an optional third parameter

[SwaggerResponse(200, typeof(CustomModel), "returns a new id of the bla bla")]

Note: The attribute is in namespace Swashbuckle.AspNetCore.Annotations

like image 14
L. Mihai Avatar answered Oct 13 '22 21:10

L. Mihai