CodeBeatz
CodeBeatz

Reputation: 1981

How can I provide example data for my request / response in Swagger UI?

I'm developing one web service with WebAPI 2 and OWIN. My goal is add some documentation with Swashbuckle.

Following my method:

/// <summary>
/// La mia descrizione...
/// </summary>
/// <param name="id">Identificativo</param>
/// <param name="list">Una lista</param>
[HttpPut]
[Route("~/api/v1/documents/{id}/attribute")]
public IHttpActionResult Put(int id, List<AttributeDto> list)
{
    _myService.Create(list, id);
    return Ok();
}

Below my AttributeDto class code:

using Newtonsoft.Json;

namespace WebApi.Dtos
{
    public class AttributeDto
    {
        [JsonIgnore]
        public int Id { get; set; }

        [JsonIgnore]
        public int OtherId { get; set; }

        public string Label { get; set; }

        public string Value { get; set; }
    }
}

If I open Swagger UI I can view one example section with autogenerated data:

Swagger UI autogenerated data example..

How can I customize autogenerated data so that JSON in picture becomes like below:

[
  {
    "label": "Etichetta di esempio",
    "value": "Valore di esempio"
  }
]

Upvotes: 4

Views: 2005

Answers (2)

Helder Sepulveda
Helder Sepulveda

Reputation: 17574

An option will be to use an ISchemaFilter (that goes on the SwaggerConfig.cs), here is an example:

private class ApplySchemaVendorExtensions : ISchemaFilter
{
    public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
    {
        if (schema.properties != null)
        {
            foreach (var p in schema.properties)
            {
                switch (p.Key)
                {
                    case "label":
                        p.Value.example = "Etichetta di esempio";
                        break;
                    case "value":
                        p.Value.example = "Valore di esempio";
                        break;
                }
                break;
            }
        }
    }
}

I personally don't love that solution because we will have to maintain information for a class in two different files...

Upvotes: 0

Helder Sepulveda
Helder Sepulveda

Reputation: 17574

I will recommend you using Swagger-Net instead of swashbuckle. All you will need to do is decorate the definition property with an xml example comment like this:

public class AttributeDto
{
    [JsonIgnore]
    public int Id { get; set; }

    [JsonIgnore]
    public int OtherId { get; set; }

    /// <example>Etichetta di esempio</example>
    public string Label { get; set; }

    /// <example>Valore di esempio</example>
    public string Value { get; set; }
}

This was proposed to swashbuckle but is has not been merge there yet:
https://github.com/domaindrivendev/Swashbuckle/pull/1091
Swagger-Net is my fork of Swashbuckle but I've merged many nice features and fixed many bugs.

Upvotes: 1

Related Questions