Provide a complex object for a SwaggerExample?

723 Views Asked by At

We're using Swagger.Net package to help with our documentation.

I'm trying to add request data to be auto-generated into my documentation and was looking at this answer that provides this code block:

[SwaggerExample("id", "123456")]
public IHttpActionResult GetById(int id)
{...}

I'm not sure how I can translate that int into a more complex object. For example:

[Route("SaveCustomThing"), HttpPost]
[SwaggerExample("thing", ???)]
public HttpResponseMessage SaveCustomThing([FromBody] Thing thing)
{...}

How do I pass a pre-configured Thing object in the SwaggerExample attribute?

1

There are 1 best solutions below

2
On

Looking at the code that attribute (SwaggerExample) takes two parameters:

        public SwaggerExampleAttribute(string parameterName, object example)
        {
            this.ParameterName = parameterName;
            this.Example = example;
        }

https://github.com/heldersepu/Swagger-Net/blob/6afdb0c1ba611273f27e8a904ec2bb06a630b1b4/Swagger.Net/Swagger/Annotations/SwaggerExampleAttribute.cs#L16

We can see the first one is a string but second is an object...
In theory you should be able to pass anything there.


Another alternative I would recommend, if you have complex models like your Thing you should consider adding the examples on the model, we can do a lot more there... as you can see below we can add description, example values and with some other decorators we can limit the range of values code looks like:

    /// <summary>
    /// ## Geographic coordinates
    /// ___
    /// A **geographic coordinate system** is a coordinate system used in geography that enables every location on Earth to be specified by a set of numbers
    /// </summary>
    public class Location
    {
        /// <summary>**Latitude**: a geographic coordinate that specifies the north–south position of a point on the Earth's surface.</summary>
        /// <example>25.85</example>
        [Range(-90, 90)]
        public float Lat { get; set; }

        /// <summary>**Longitude**: a geographic coordinate that specifies the east-west position of a point on the Earth's surface.</summary>
        /// <example>-80.27</example>
        [Range(-180, 180)]
        public float Lon { get; set; }
    }

http://swagger-net-test.azurewebsites.net/swagger/ui/index#/Location/Location_Get2