Kaladin
Kaladin

Reputation: 803

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

Upvotes: 38

Views: 60292

Answers (3)

Elton
Elton

Reputation: 1513

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<IEnumerable<YourModel>>(StatusCodes.Status200OK)]

ProducesResponsesType is in Microsoft.AspNetCore.Mvc namespace.

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

Upvotes: 38

L. Mihai
L. Mihai

Reputation: 246

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

Upvotes: 21

EvilToaster101
EvilToaster101

Reputation: 573

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.

Upvotes: 55

Related Questions