23

Is there a way to specify example requests for swagger? Maybe even multiple ones?

The Try it out button shows only generic values like:

{
    "firstName": "string",
    "lastName": "string"
}

for

public class User
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

It becomes very difficult to use with large objects when you have to edit all the values first. I know I could use Postman, and I do too, but being able to create multiple good looking and useful examples with swagger would be very nice.

Helen
  • 87,344
  • 17
  • 243
  • 314
t3chb0t
  • 16,340
  • 13
  • 78
  • 118
  • @ArtemIgnatovich nope, this isn't it. I'm lookig for example/test values and possible for multiple requests for trying out the API. Setting default values is _easy_ and they are not the same thing. – t3chb0t Jul 26 '19 at 12:26
  • I haven't heard of this feature before. @t3chb0t now it is clear what you've meant. You can render a section (using plain html) with examples with formatted data (to copy and paste it into the try it out window), but I dont think it is possible in "try it out" section. – Artyom Ignatovich Jul 26 '19 at 12:30
  • 1
    One more option to try is to investigate a built-in plugin system for swagger-ui or already existing public extensions (there is also a room for writing your own and get some stars at github he-he). – Artyom Ignatovich Jul 26 '19 at 12:37
  • @ArtemIgnatovich I think I've found it, see _Request Body Examples_ [here](https://swagger.io/docs/specification/describing-request-body/) – t3chb0t Jul 26 '19 at 12:43
  • Good to know! There is always a room for learning something new even if you are 99% sure that this does not exist. – Artyom Ignatovich Jul 26 '19 at 12:53
  • Do you use Swashbuckle or Swagger-Net? They probably provide annotations to customize property examples. – Helen Jul 29 '19 at 17:17
  • @Helen this would mean only a single example; see the link in my previous comment, it's possible with extra configs – t3chb0t Jul 30 '19 at 10:00
  • 2
    See if this helps: https://github.com/mattfrear/Swashbuckle.AspNetCore.Filters#how-to-use---request-examples – Helen Jul 30 '19 at 10:13
  • @Helen cool, this is pretty interesting ;-) – t3chb0t Jul 30 '19 at 10:16

2 Answers2

18

With ASP.NET Core 3.1, Swagger OAS 3 and Swashbuckle.AspNetCore 5.4.1, the following model class + XML comments works for me:-

    /// <summary>
    /// A user.
    /// </summary>
    public class User
    {
        /// <summary>
        /// The user's first name.
        /// </summary>
        /// <example>Jane</example>
        public string FirstName { get; set; }

        /// <summary>
        /// The user's last name.
        /// </summary>
        /// <example>Austin</example>
        public string LastName { get; set; }
    }

Now when I click "Try it Out" (for a POST operation that takes a User model in the message body), I get the defaults:-

{
    "firstName": "Jane",
    "lastName": "Austin"
}
Bellarmine Head
  • 3,397
  • 2
  • 22
  • 31
  • I currently cannot try it out but does it mean that Swagger can read the `example` element of the comment? – t3chb0t May 22 '20 at 13:30
  • 2
    I'm not sure if it's Swagger or Swashbuckle doing the work here (or maybe they both are), but basically yes: it's reading the `` XML comment and using that value as the default value when doing "Try it out". – Bellarmine Head May 22 '20 at 14:56
  • 1
    @AndrewWebb I have posted the question yesterday with the same requirement, my question has been linked here and I got your answer. I have tried doing the same, provided all the relevant technologies are same as mentioned in my application. Is there any configuration needed or can you share further what else required to see this. – Monibrata Sep 17 '21 at 04:24
  • 2
    @Monibrata if the types are in a different project, make sure you are outputting XML documentation for that project, and add the file to IncludeXmlComments in the SwaggerGenOptions see https://stackoverflow.com/a/50837958/914352 – NMrt Dec 14 '21 at 11:58
17

In .Net5 you can add a SchemaFilter to Swagger in the Startup.cs

public override void ConfigureServices(IServiceCollection services)
{
    services.AddSwaggerGen(c =>
    {
        c.SchemaFilter<ExampleSchemaFilter>();
    });
}

In the ExampleSchemaFilter.cs you simply define an OpenApiObject for your specific class:

using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

public class ExampleSchemaFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        if (context.Type == typeof(User))
        {
            schema.Example = new OpenApiObject()
            {
                ["firstName"] = new OpenApiString("John"),
                ["lastName"] = new OpenApiString("Doe"),
            };
        }
    }
}
Matthias Müller
  • 444
  • 6
  • 15
  • Can you please provide an example of how `ExampleSchemaFilter` would be used in code? – Mass Dot Net Jun 18 '22 at 22:13
  • 1
    My answer is the example how to use the ExampleSchemaFilter in code. In .AddSwaggerGen() you register the ExampleSchemaFilter and in this case Swagger automatically sets the values in the Try it out with the values you gave the object in the SchemaFilter. – Matthias Müller Jun 20 '22 at 09:21
  • My bad -- I thought it needed to be applied as an attribute. Thank you! – Mass Dot Net Jun 21 '22 at 14:22