Generating Swagger example responses with Swashbuckle

Update April 2020: You probably don’t need to do it this way any more. Swashbuckle.AspNetCore supports request examples via XML comments. See my blog post.

Update May 4th 2017: I have created a new NuGet package called Swashbuckle.Examples which contains the functionality I previously described in this blog post. The code lives on GitHub.

I have also created a .NET Standard version of the NuGet package at Swashbuckle.AspNetCore.Filters, which is also on GitHub.

Swashbuckle is a tool for generating Swagger, the API description language, from your ASP.NET Web Api solution.
Using Swashbuckle, which provides Swagger-UI, you can create pretty living documentation of your web api, like this:
swagger

Documenting the Response

In this post I am going to show you how to document the Response, and a new way to generate some response examples.

You can specify the type of response for Swashbuckle a number of ways. Consider a simple API endpoint which returns a list of Countries:

public class CountriesController : DefaultController
{
    [HttpGet]
    public async Task<HttpResponseMessage> Get()
    {
        var resource = new List<Country>
        {
            new Country {Code = "AR", Name = "Argentina"},
            new Country {Code = "BR", Name = "Brazil"},
            // etc etc omitted for brevity
        };

        return Request.CreateResponse(HttpStatusCode.OK, resource);
    }
}

One way of describing the response code and content for Swashbuckle is using a combination of XML comments, and the ResponseType attribute, like so:

/// <response code="200">Countries returned OK</response>
[HttpGet]
[ResponseType(typeof(IEnumerable<Country>))]
public async Task<HttpResponseMessage> Get()
{

However, this only allows for one type of response.

If your API method can return multiple types, i.e. in the case of an error, then you can use the new SwaggerResponse attribute:

[HttpGet]
[SwaggerResponse(HttpStatusCode.OK, Type=typeof(IEnumerable<Country>))]
[SwaggerResponse(HttpStatusCode.BadRequest, Type = typeof(IEnumerable<ErrorResource>))]
public async Task<HttpResponseMessage> Get(string lang)
{

The Swagger 2.0 spec allows for examples to be added to the Response. However, at time of writing Swashbuckle doesn’t support this. Fortunately Swashbuckle is extendible so here is a way of doing it.

Install my Swashbuckle.Examples NuGet package.

Decorate your methods with the new SwaggerResponseExample attribute:

[SwaggerResponse(HttpStatusCode.OK, Type=typeof(IEnumerable<Country>))]
[SwaggerResponseExample(HttpStatusCode.OK, typeof(CountryExamples))]
[SwaggerResponse(HttpStatusCode.BadRequest, Type = typeof(IEnumerable<ErrorResource>))]
public async Task<HttpResponseMessage> Get(string lang)

Now you’ll need to add an Examples class, which will implement IExamplesProvider to generate the example data

public class CountryExamples : IExamplesProvider
{
    public object GetExamples()
    {
        return new List<Country>
        {
            new Country { Code = "AA", Name = "Test Country" },
            new Country { Code = "BB", Name = "And another" }
        };
    }
}

And finally enable the ExamplesOperationFilter when you configure Swashbuckle’s startup.

configuration
    .EnableSwagger(c =>
    {
        c.OperationFilter<ExamplesOperationFilter>();
    })
    .EnableSwaggerUi();

Now that we’ve done all that, we should see the examples output in our swagger.json file, which you can get to by starting your solution and navigating to /swagger/docs/v1.

response

And then, when you browse the swagger-ui at /swagger/ui/index, instead of an autogenerated example like this:
response old

You’ll see your desired example, like this:
response new

Be sure to check out Part 2, where we again use Swashbuckle to generate example requests.

61 thoughts on “Generating Swagger example responses with Swashbuckle

  1. We were rockin’ swagger briefly here for our web APIs (Java though, not .net). Has to be one of the most incongruently named technologies out there.

    Good to hear swashbuckle is continuing the tradition.

  2. Thanks for the article, helped me construct my own example response scheme. Have you tried doing the same for providing example values to HTTP POST request parameters which are given as JSON in the request body? Would be nice to hear if you have any insight how to go about those.

  3. I have both [ResponseType] and [SwaggerResponse] attributes on my controller methods. When I enable xml comments, these are not reflected anymore and my documentation shows an empty response object.

    Is there any way to use xml comments for summary, remarks, etc and still have response types generated from code?

    • Hmm yes I think it should work – in our solution we have both xml comments and SwaggerResponse.

      It might be worth checking on the Swashbuckle github page as things may have changed in newer versions.

  4. Hi
    I have done the same thing, but i am unable to see the examples values what I defined the examples class.
    Showing only default values.

    Regards,
    Ajay

  5. How have the response several requests bad errors with different messages? And that appears in the documentation swagger

    Regards, Michel

    • Just add multiple SwaggerResponse attributes to your controller method, e.g.

      [SwaggerResponse(HttpStatusCode.OK, Type = typeof(DeliveryOptionsModel), Description = “Delivery options for the country found and returned successfully”)]
      [SwaggerResponseExamples(typeof(DeliveryOptionsModel), typeof(DeliveryOptionsModelExample))]
      [SwaggerResponse(HttpStatusCode.BadRequest, Type = typeof(ErrorsModel), Description = “An invalid or missing input parameter will result in a bad request”)]
      [SwaggerResponse(HttpStatusCode.InternalServerError, Type = typeof(ErrorsModel), Description = “An unexpected error occurred”)]
      public async Task DeliveryOptionsForCountry([FromUri]DeliveryOptionsForCountryRequestModel search)

      • ok, yes, I understand. But, and how do I several different messages of the same type of HTTP error, in case the bad request.
        Example:
        [Swagger Response (HttpStatusCode.BadRequest, Type = typeof (Error Model), Description = “Message 1”)]
        [Swagger Response (HttpStatusCode.BadRequest, Type = typeof (ErrorsModel), Description = “Message 2”)]
        [SwaggerResponse (HttpStatusCode.BadRequest, Type = typeof (ErrorsModel), Description = “Message 3”)]
        You understand?

  6. I’m not sure if what you want to generate is valid swagger.
    http://swagger.io/specification/#responsesDefinitionsObject

    Well, a response name (e.g. BadRequest) can only have one description, but I guess there’s nothing in the spec which says each name has to be unique.

    I don’t know the answer to your question, but you could try asking on Swashbuckle’s github page – the SwaggerResponse attribute is part of Swashbuckle and is not my work.

    Matt

  7. Hi, thanks for the great post. Is there any way to add request/response examples without using swagger specific attributes in controllers? Because I am looking for a way where controller classes need not be tightly coupled with swashbuckle.

  8. Matt,

    Like the post have a question I am not a .Net expert, but got Swashbuckle working and Auto-Generating the swagger documentation. Since we are using the Web API documentation generator we have one object type in the model that is wonky from a REST API point of view.

    The Model definition looks like this (replaced some values for ease of reading) Engine.Api.Facade.ApiResult[System.Collections.Generic.IEnumerable[Engine.Api.ResourceModels.Public.Reporting.Performance.PerformanceByDayReportRow]] {…}

    So wondering, based on what I read here, I can generate custom data definition to remove the IEnumerable (this being REST) and simplify things since no need to expose the underlying data structures.

    Is that a correct understanding?

    • Hi Kevin,

      No, I don’t think you are correct. If your model is an IEnumerable then by default Swashbuckle will report that. I’m not a Swashbuckle or a Swagger expert though.

      My post was describing how to add some example data to your Model so that you get useful data in the generated Swagger. You might be able to use it to change the shape of your model but I don’t think it would work (I haven’t tried it).

      There’s nothing wrong with returning an IEnumerable though. I guess you could put it in a container object to be my RESTy perhaps, but I don’t think that is necessary. e.g.

      public class Report
      {
      public IEnumerable Rows { get; set; }
      public int Count { get; set; }
      }

      • yeah I want it to me more “RESTy” as IEnumerable is really not in any spec. That said I am exploring some options and our devs are looking at possible way to return a more REST like documentation response.

        I’ll do my best to update this if I glean anything useful

  9. My “X.Value.schema” is Null. Here is the comments i have above my method. Any ideas what I am missing?

    ///
    /// Post for entry properties
    ///
    ///
    /// This is the example
    ///
    ///
    /// LanguageID will default to 0.
    ///
    /// POST /PropertyEntry
    /// {
    /// “PropertyIds”: [
    /// 100,200,240
    /// ],
    /// “EntryIds”: [
    /// 15888,15889,15890
    /// ],
    /// “Language”: “en”,
    /// }
    ///
    ///
    /// Returns property Range
    /// Example: returns new item
    /// Example: Returns the range
    /// Example: If the item is null

    • Well it doesn’t like greater than/less than symbols. I see now. I have in the comments summary, example, remarks, param, returns, and response. Thanks!

  10. Any Idea how to decorate an endpoint so that swashbuckle can understand Response Headers being returned? I would assume that there should be some type of override in ProducesResponseType that would include a dictionary of headers that will be returned. I cannot find any documentation about this, and it seems like it really should be there. Thanks
    Marc

  11. Great library to easily generate examples to display on swagger ui. However, I am having one issue with the json request and response property’s case. I have declared models in c# as PascalCase and I want all properties to appear as pascal case as well on the documentation page. However, on the documentation page, swagger ui automatically converts all property names to camelCase. I found a solution to change in swagger ui to define default contract resolver like below and then it shows property names to PascalCase. but this solution does not work with methods decorated with Swaggerexamples:

    [SwaggerResponseExample(HttpStatusCode.OK,typeof(UserLoginResponseExample))]

    Default contract resolver solution:

    config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver();

    • There is a an optional contract resolver parameter for the attribute. You can use it like this to make your response example to be PascalCase :

      [SwaggerResponseExample(HttpStatusCode.OK, typeof(UserLoginResponseExample), typeof(DefaultContractResolver))]

  12. You might update this post to show the interface as IExamplesProvider instead of IProvideExamples. I think it got renamed at some point?

  13. Hi mattfrear,

    I am getting this error “Could not load file or assembly ‘Swashbuckle.Examples, Version=2.3.0.0, Culture=neutral, PublicKeyToken=null’ or one of its dependencies. A strongly-named assembly is required. (Exception from HRESULT: 0x80131044)” in NSwag studio while loading the assemblies.

    I have installed Swashbuckle.Examples in nuget package and also downloaded your code from github, attached the Swashbuckle.Examples project to my solution and referenced it. Still always got this error.

    • I’ve never heard of NSwag studio, but it sounds like it needs a strongly-named assembly. I have signed Swashbuckle.Examples with a cert for you and just uploaded it to NuGet, so if you try install Swashbuckle.Examples version 3.0 it should work.

      PS. Swashbuckle.AspNetCore.Examples has also been strong named – that is version 2.0.

  14. In the screenshot of your swagger definition file it shows “examples” : { “application/json”: {
    But when I add the responses it is not showing the “application/json” part, Has this been removed in a later version?

  15. Hi,
    I’m glad I’ve found this post and tried this lib immediately!
    But I found one unexpected behavior. Json is generated the same as expected, but UI response example shows property ‘application/json’. It shows example:
    {
    “application/json”: {
    “id”: 1
    }
    }
    but I would expect to see:
    {
    “id”: 1
    }

    Maybe you know, where the issue is?

    • Yes, that started happening with more recent versions of Swashbuckle.
      The Swagger that I am outputting is valid Swagger, so I’m not sure why Swagger-UI is displaying it incorrectly. I have found a workaround but I haven’t had time to implement it yet.

  16. Hi,

    how can i convert my request model example into pascal case.
    [SwaggerRequestExample(typeof(LeadDto), typeof(LeadEntityModelExample), typeof(DefaultContractResolver))]

    i am using above approach but it still converting my model into camael case.
    i am using swash buckle 5.6.0 latest version.

    any help.

    thanks

  17. Hi,

    I have an object in my request which contains two properties of Enum type.

    “sortInfo”: {
    “fieldName”: 0,
    “order”: 1
    }

    As you can see that swagger is printing the int values of Enums in request example, which are not pretty much understandable. Is there a way to display the string values of Enums?

  18. Great library and informative blog.

    However when I used this, I get strange output in the Swagger UI.

    Instead of seeing the example I generated

    {
    “MyProperty1”: “MyValue1”.
    “MyProperty2”, “MyValue2”
    }

    I’m seeing:

    {
    “application/json”: {
    “MyProperty1”: “MyValue1”.
    “MyProperty2”, “MyValue2”
    }
    }

    Any idea how to get rid of the unwanted “application/json” wrapper.

      • Thanks for responding. So you are leaving the wrapper for conformance with the Swagger spec, even though the current UI displays it incorrectly. I wonder whether it would be worth having an optional constructor parameter for SwaggerResponseExampleAttribute to switch the wrapper on / off (e.g. bool strictConformance).

        But in any case I can point my users who are complaining at the GitHub issue which says it’s most probably a swagger ui issue.

  19. Hi Matt,

    Would it be possible to use [SwaggerDescription(“use this API to check the get the country list”)] to the API?

    Like:
    [SwaggerDescription(“use this API to check the get the country list”)]
    public async Task Get()
    {

    And it can be used instead of the XML comment?

  20. Hi, I’m tring to use this on my .Net 4.7.1 project.

    But only the response 200 is coming with the example, the others statuscode’s don’t.

    Would you know what could be the error?

  21. Hi Matt,

    Thanks for the useful post for generate swagger file in web API.

    I have a question.

    I would like to know whether we can generate separate swagger URL for the individual apis. This is because I need to import them to Azure API Gateway one by one rather than importing them as a whole. Below is the structure of my project. Currently the Swashbuckle library generates a single Swagger URL for all the apis in the project.

    Solution
    Project A
    Controller 1
    API – 1 GET
    API – 2 POST
    API – 3 GET

    Project B
    Controller 2
    API – 1 GET
    API – 2 POST
    API – 3 GET

    • Hi Rao,

      That sounds like a question for the author of Swashbuckle rather than for me. I don’t know of a way to do what you’ve asked for. You might have to hand-edit the Swagger file to get what you need.

      Matt

  22. Hey, awesome work on this. I was just testing it and it works brilliantly. One thing I notice – and it’s probably the way I’ve set it up – but in Swagger UI, If I set response content type to XML, then the response body I receive is in XML but the example doesn’t change – it’s always json. Is there a way to make the Example value match the requested content type?
    Thanks

  23. Hi , I want Error Response Object Array which show Error Code , Error Description and Type in one array object have different item under this for each error code .Please suggest how we can do this

    • You can specify a different example for each response code, like so:

      [SwaggerResponse(HttpStatusCode.OK, Type=typeof(IEnumerable<Country>))]
      [SwaggerResponseExample(HttpStatusCode.OK, typeof(CountryExamples))]

      [SwaggerResponse(HttpStatusCode.BadRequest, Type = typeof(IEnumerable<ErrorResource>))]
      [SwaggerResponseExample(HttpStatusCode.BadRequest, typeof(BadRequestExample))]

      [SwaggerResponse(HttpStatusCode.NotFound, Type = typeof(IEnumerable<ErrorResource>))]
      [SwaggerResponseExample(HttpStatusCode.NotFound, typeof(NotFoundExample))]

      [SwaggerResponse(HttpStatusCode.Conflict, Type = typeof(IEnumerable<ErrorResource>))]
      [SwaggerResponseExample(HttpStatusCode.Conflict, typeof(ConflictExample))]

  24. Hello Matt,

    i’m not able to use your package because i have a cimpoliation error in startup.
    VisualStudio underline the instructions OperationFilter() in swaggerGenOptions.
    It displays this message :
    class Swashbuckle.Examples.ExempleOperationFilter
    CS0311 : Not possible to use the type ‘Swashbuckle.Examples.ExempleOperationFilter’ as parameter of type ‘Tfilter’ in the type or the generic method ‘SwaggerGenOptionsExtensions.OperationFilter(SwaggerGenOptions, params object[])’. There is no reference conversion of ‘Swashbuckle.Examples.ExempleOperationFilter’ to ‘Swashbuckle.AspNetCore.SwaggerGen.IOperationFilter’

    The type ‘Swashbuckle.Examples.ExempleOperationFilter’ must be convertible to ‘Swashbuckle.AspNetCore.SwaggerGen.IOperationFilter’ in order to use it as parameter ‘TFliter’ in the generic method ‘void Microsoft.Extensions.DependencyInjection.SwaggerGenOptionsExtensions.OperationFilter(this SwaggerGenOptions, params object[])’

    I’using Swashbuckle.AspNetCore 5.6.3 and your package Swashbuckle.AspNetCore.Filters.Abstractions 7.0.2

    Am I doing something wrong ?

    Please Help !

Leave a comment