C
C#3w ago
Zylvian

✅ Is there a good way to add example input values to your OpenAPI spec?

Is there a good way to add example values to your OpenAPI spec so that e.g my Scalar playground has an example date ready, instead of typing a UTC datetime every time? .NET 9 btw
2 Replies
m8
m83w ago
Yes, in .NET 9 (or even .NET 6/7/8), you can add example values to your OpenAPI spec so that tools like Scalar Playground, Swagger UI, or Postman prefill example data like a UTC datetime — saving you from typing it manually each time. 1. Using [SwaggerSchema] or [Example] attributes (recommended in .NET 7+) For a model class: using Swashbuckle.AspNetCore.Annotations; public class MyRequest { [SwaggerSchema(Description = "Date in UTC", Format = "date-time", Example = "2025-01-01T00:00:00Z")] public DateTime Timestamp { get; set; } } 2. Using ISchemaFilter for richer control Create a custom schema filter to inject examples at runtime: using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; public class ExampleSchemaFilter : ISchemaFilter { public void Apply(OpenApiSchema schema, SchemaFilterContext context) { if (context.Type == typeof(DateTime)) { schema.Example = new OpenApiString("2025-01-01T00:00:00Z"); } } } Register it in Program.cs: builder.Services.AddSwaggerGen(c => { c.SchemaFilter<ExampleSchemaFilter>(); });
Unknown User
Unknown User3w ago
Message Not Public
Sign In & Join Server To View

Did you find this page helpful?