I’ve been working on a small IoT project where we expose a simple REST API and use RavenDB Embedded as the database. Once we enabled Swagger on our project we noticed that the generated documentation was not only showing our API but those exposed by RavenDB too. So the question came up: how can we Remove RavenDb’s API from Swagger Documentation?

Turns out that Swashbuckle.Swagger let’s you create your own Document Filters implementing the IDocumentFilter interface.

Below you’ll find the fast solution I came up with, and it’s easy to modify if you need to remove any other type from your Swagger documentation.

 1    using Swashbuckle.Swagger;
 2    using System.Collections.Generic;
 3    using System.Linq;
 4    using System.Web.Http.Description;
 5
 6    public class HideRavenDocumentFilter : IDocumentFilter
 7    {
 8        public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
 9        {
10            foreach (var apiDescription in apiExplorer.ApiDescriptions)
11            {
12                if (!apiDescription.ActionDescriptor.ControllerDescriptor.ControllerType.Namespace.StartsWith("Raven"))
13                {
14                    continue;
15                }
16
17                var routeToRemove = swaggerDoc.paths.Where(r => r.Key.Contains(apiDescription.ActionDescriptor.ControllerDescriptor.ControllerName))
18                    .FirstOrDefault();
19
20                if (!routeToRemove.Equals(default(KeyValuePair<string, PathItem>)))
21                {
22                    swaggerDoc.paths.Remove(routeToRemove);
23                }
24            }
25        }
26    }

Hope it helps!