Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Models from External package are showing in swagger docs

I am working on swagger documentation and added an external package "NodaTime" and used as type for my properties in models public LocalDateTime Date { get; set; } and models from NodaTime package are showing in docs. please see models in the screenshot, highlighted are from NodaTime package. Why Swagger including it in the docs and how to exclude external package from docs. enter image description here Thanks in advance.

like image 555
Malik Rizwan Avatar asked Jul 24 '18 06:07

Malik Rizwan


2 Answers

I'm guessing they are showing up because you are exposing an object that uses the NodaTime type. Swashbuckle / Swagger is showing the entire object graph... There is no way to turn off third party things like that if you models use those models. If you look at the code in the library on github, you can see that Swashbuckle gives special treatment to several base class library primitives. The method is CreatePrimitiveSchema(), LocalDateTime is not in the case statement. Therefore, as a fix for this you could fork Swashbuckle and add in NodaTime types. This may not be worth it.

However, Swashbuckle allows you to turn off the model expansion. Below you can see how I have my Swashbuckle config setup. Setting DefaultModelsExpandDepth(-1) will hide them.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, DataGraphContext db) {
        if (env.IsDevelopment()) {
            app.UseDeveloperExceptionPage();
        } else {
            app.UseHsts();
        }

        app.UseSwagger();

        app.UseSwaggerUI(c => {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "API V1");
            c.DefaultModelExpandDepth(0);
            c.DefaultModelsExpandDepth(-1);
        });

        app.UseAuthentication();

        app.UseExceptionHandling();
        app.UseCors("AllowSpecificOrigins");
        app.UseHttpsRedirection();
        app.UseMvc();
    }
like image 56
GetFuzzy Avatar answered Oct 22 '22 09:10

GetFuzzy


i can't use the DefaultModelExpandDepth(0); because this will hide my own models, i am using as a type in models. so, i used to check which types are coming from external package and excluded them like below.

Add filter

public class RemoveVerbsFilter : IDocumentFilter
{
    public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
    {
        swaggerDoc.Definitions.Remove("LocalDateTime");
        swaggerDoc.Definitions.Remove("CalendarSystem");
        swaggerDoc.Definitions.Remove("Era");
        swaggerDoc.Definitions.Remove("LocalTime");
        swaggerDoc.Definitions.Remove("LocalDate");
    }
}

Add in startup class ConfigureServices method

    services.AddSwaggerGen(c =>
        {
            c.DocumentFilter<RemoveVerbsFilter>();
        });
like image 25
Malik Rizwan Avatar answered Oct 22 '22 08:10

Malik Rizwan