Search code examples
c#openapiasp.net-minimal-apis

How to add body parameter examples to OpenApi in MinimalApi


So we have minimal API implementation and would like to add swagger documentation for request/response.

What I don't know how to achieve is how to annotate request body parameters and responses with example values for the caller. We are using RouteHandlerBuilder to add swagger documentation with OpenApi, and for response we have following code:

builder.Produces<ResponseModel>(HttpStatusCode.OK, description);

and this will properly show response model but with default data for properties, like: "Name" : "string".

What I'm trying to do is to add example value to the response body instead of default type value. Usually, what I would do would be to add /// summary and /// example comments over the model but is there more elegant way for doing this using OpenApi library?


Solution

  • Best solution that I currently came up with is the extension of builder that put's stringified body example to response using OpenApi

    builder.WithOpenApi(c => {
        var statusCodeKey = ((int) statusCode).ToString(CultureInfo.InvariantCulture);
        if (example != null) {
            c.Responses[statusCodeKey].Content[contentType].Example = new OpenApiString(JsonSerializer.Serialize(example));
        }
        return c;
    });
    

    Soluition sets example to different status codes so we can reuse this to set example for 200/201 response but also various error response examples.