joostas
joostas

Reputation: 581

Asp.NET Core 7.0 Minimal API: OpenAPI how to specify correct DateOnly type representation

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

Answers (1)

pfx
pfx

Reputation: 23314

  1. Add a type mapping for DateOnly in the AddSwaggerGencall.
builder.Services.AddSwaggerGen(
    options => options.MapType<DateOnly>(() => new OpenApiSchema()
    {
        Type = "string",
        Format = "date"
    }));
  1. In the 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.

enter image description here

"/info": {
  "get": {
    "tags": [
      "MyWebApplication"
    ],
    "parameters": [
      {
        "name": "date",
        "in": "query",
        "required": true,
        "style": "form",
        "schema": {
          "type": "string",
          "format": "date"
        }
      }
    ],

Upvotes: 6

Related Questions