0

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?

Helen
  • 87,344
  • 17
  • 243
  • 314
LarsTech
  • 80,625
  • 14
  • 153
  • 225

1 Answers1

1

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

Helder Sepulveda
  • 15,500
  • 4
  • 29
  • 56
  • I don't see how the attribute gets decorated. I'm still stuck with `[SwaggerExample("location", Location???)]` I don't know what I'm passing for an object. – LarsTech Nov 29 '21 at 15:49
  • There is no `SwaggerExample("location"` those are on the model at each individual property `/// 25.85` I added the code sample there – Helder Sepulveda Nov 29 '21 at 17:39