Reputation: 581
In minimal API I define this endpoint that accepts DateOnly
parameter:
app.MapGet("/info", (DateOnly date) => $"{date.ToString("yyyy-MM")}";
By default swagger json is generated with parameter schema as string:
"/info": {
"get": {
"tags": [
"MinimalApi"
],
"parameters": [
{
"name": "date",
"in": "query",
"required": true,
"style": "form",
"schema": {
"type": "string" // <--
}
}
],
OpenAPI allows to define additional string formats link:
An optional format modifier serves as a hint at the contents and format of the string. OpenAPI defines the following built-in string formats:
date – full-date notation as defined by RFC 3339, section 5.6, for example, 2017-07-21
So I want that my parameter would have additional format information and look like this:
"parameters": [
{
"name": "date",
"in": "query",
"required": true,
"style": "form",
"schema": {
"type": "string",
"format": "date" // <-- additional format
}
}
Therefore I tried to add this information using WithOpenApi
extension method:
app.MapGet("/info", (DateOnly date) => $"Experimenting with APIs {date.ToString("yyyy-MM")}")
.WithOpenApi(o => {
o.Summary = "Summary is added";
o.Parameters[0].Description = "Description is added";
o.Parameters[0].Schema = new(){ Format = "date", Type = "string" }; //this doesn't change
return o;
});
But this doesn't help. Now generated swagger.json
has additional info, but parameter schema isn't changed:
"summary": "Summary is added", //<-- added
"parameters": [
{
"name": "date",
"in": "query",
"description": "Description is added", //<-- added
"required": true,
"style": "form",
"schema": {
"type": "string" //<-- was not changed
}
}
]
Question: how can I update schema of parameter and add format information into it (when using minimal API)?
Upvotes: 5
Views: 1816
Reputation: 23314
DateOnly
in the AddSwaggerGen
call.builder.Services.AddSwaggerGen(
options => options.MapType<DateOnly>(() => new OpenApiSchema()
{
Type = "string",
Format = "date"
}));
MapGet
call, mark the DateOnly date
argument with a FromQuery
attribute.app.MapGet("/info", ([FromQuery] DateOnly date) => $"{date.ToString("yyyy-MM")}");
Above steps give the expected result, both in the Swagger UI and json definition.
"/info": {
"get": {
"tags": [
"MyWebApplication"
],
"parameters": [
{
"name": "date",
"in": "query",
"required": true,
"style": "form",
"schema": {
"type": "string",
"format": "date"
}
}
],
Upvotes: 6