Home > other >  How to add example value to openapi.json in ASP.NET Core?
How to add example value to openapi.json in ASP.NET Core?

Time:10-12

In OpenAPI 3.0, there is a Adding Examples feature. I can add some example value to the Swagger UI. I'm using ASP.NET Core 6 Web API. Is it possible add these example value to the API action and reflect these example values to the openapi.json that generated by ASP.NET Core automatically?

CodePudding user response:

By utilizing <example>

public class MyRequest
{
    /// <summary>
    /// Email parameter.
    /// </summary>
    /// <example>[email protected]</example>
    [Required]
    public string Email { get; set; }
}

and adding this in your Startup.cs

services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title = "My Good API",
                    Version = "v1",
                    Description = "Doesn't hurt to add some description."
                });

                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });

Bumping up @CodingMytra's suggestion, for more options see here and here

  • Related