NewDev90
NewDev90

Reputation: 399

Displaying object types for object[] in Swagger using Swashbuckle

This might be a non-trivial question, but using C# (.Net Core 3.1), I am generating swagger profiles using Swashbuckle.

One of the models (external service provider) contains a field of the form object[], that can take on two different types of objects:

Object1 {
   Field1
   Field2
}

Object2 {
   Field1
   Field2
}

Is it possible somehow to document this in swagger? By default the object[] will be shown as follows in Swagger:

MyObject [
    null
]

Ideally I would like to show examples of what this null object can actually be.

Is this possible?

Please note the model in question is provided by an external service, I am just trying to figure out if it is possible to provided some meaningful documentation in Swagger for the customers using the application I am part of building.

Upvotes: 2

Views: 1673

Answers (1)

Sarath Pantula
Sarath Pantula

Reputation: 1

Swagger is the best way to show the documentation, Now in order to get the model classes of the return types, I would suggest you to add the "ProducesResponseType" attribute on top of your method. Here is how the Startup.cs is going to look like.

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {

        services.AddControllers();
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo
            {
                Title = "Your Api name",
                Version = "v1",
                Description = "A simple example ASP.NET Core Web API",
                TermsOfService = new Uri("https://example.com/terms"),
                Contact = new OpenApiContact
                {
                    Name = "Custom Name",
                    Email = string.Empty,
                    Url = new Uri("https://linkedin.com/sampleurl"),
                },
                License = new OpenApiLicense
                {
                    Name = "Use under LICX",
                    Url = new Uri("https://example.com/license"),
                }
            });

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

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();

        }
        app.UseSwagger(c =>
        {
            c.SerializeAsV2 = true;
        });

        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "Your Api name");
        });

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }

Now, that you have configured swagger in your startup.cs, it's time to use them in your controller.

[Route("api/[controller]")]
[ApiController]
public class SampleController : ControllerBase
{
    /// <summary>
    /// Sample Summary
    /// </summary>
    /// <param name="param1">About Param 1</param>
    /// <param name="param2">About Param 2</param>
    /// <returns></returns>
    [HttpGet]
    [Route("{ipAddress}")]
    [ProducesResponseType(typeof(SampleResponse), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)]
    public async Task<IActionResult> GetSecurityDataAsync([FromRoute] string param1, [FromQuery] string param2)
    {
        try
        {
            //Custom logic
        }
        catch (Exception)
        {

            throw;
        }
    }
}

Note: Make sure that the XmlDocumentFilepath under the Output section of the Build tab within the Project properties is checked. Project Properties

Upvotes: -2

Related Questions