Swagger expand on possible endpoints

Viewed 594

I am currently use Swagger to expose all my endpoints, but these endpoints are currently formatted as: /get/{name}, /put/{name}, where the name can only be those names which I have in database?

Is somehow possible to make swagger expand the general API definition to contain all possible API call one could make, meaning all possible names?

1 Answers

I am assuming you are using .NET Core.
I have not tested this solution, but hopefully it is on the right track.

In your Startup class, you are probably registering Swagger in the ConfigureServices method, as well as your database context.

You need to add one line in AddSwaggerGen to register a custom filter.

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<YourContext>();

    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });

        // Custom filter (could also be a SchemaFilter)
        c.ParameterFilter<CustomParametersFilter>();
    });
}

Here is the CustomParametersFilter class:

public class CustomParametersFilter : IParameterFilter
{
    private readonly YourContext dbContext;

    public CustomParametersFilter(YourContext dbContext)
    {
        // Here you also have access to IServiceProvider or any dependency
        this.dbContext = dbContext;
    }

    public void Apply(IParameter parameter, ParameterFilterContext context)
    {
        if (parameter.Name == "some_name")
        {
            // Use dbContext to retrieve your values
            List<string> validValues;
            // ...

            parameter.Description = string.Join(", ", validValues);
        }
    }
}

The code for CustomParametersFilter is a starting point, but it can be adjusted to suit your needs. IParameter (and OpenApiParameter) offer many more options.

Related