I’m creating an api where an arbitrary number of query parameters can be added.
The API looks something like this:
GET /api/example?param1=value1¶m2=value2¶m3=value3
By default when Swashbuckle generates the Swagger UI it only includes parameters that are explicitly defined at the action method level.
Luckily the Open API spec supports this starting from version 3 through ‘free form query parameters’.
At the spec level this looks like this:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
openapi: 3.0.1 | |
paths: | |
/example: | |
get: | |
parameters: | |
- in: query | |
name: params | |
schema: | |
type: object | |
additionalProperties: | |
type: string | |
# `style: form` and `explode: true` is the default serialization method | |
# for query parameters, so these keywords can be omitted | |
style: form | |
explode: true |
To achieve this using Swashbuckle you can use an operation filter:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class QueryParametersFilter : IOperationFilter | |
{ | |
public void Apply(OpenApiOperation operation, OperationFilterContext context) | |
{ | |
if (!context.MethodInfo.Name.StartsWith("UploadDocument")) | |
return; | |
operation.Parameters.Add(new OpenApiParameter() | |
{ | |
In = ParameterLocation.Query, | |
Name = "params", | |
Schema = new OpenApiSchema() | |
{ | |
Type = "object", | |
AdditionalProperties = new OpenApiSchema() | |
{ | |
Type = "string" | |
} | |
}, | |
Style = ParameterStyle.Form, | |
Explode = true, | |
}); | |
} | |
} |
This will generate the following UI: