I have a new .NET6 Azure Functions application. I created a few HTTP functions with OpenAPI specifications.
My swagger page is working fine, except for the POST function.
I would like to show a minimal body request on this page as an example.
I've implemented IOpenApiExample
as mentioned at https://github.com/Azure/azure-functions-openapi-extension/blob/main/docs/openapi-core.md#openapirequestbodyattribute
but the example is not used. It keeps showing the whole model without any sample values.
This is my relevant code:
[FunctionName("PostHistoryEvent")]
[OpenApiOperation(operationId: "PostHistoryEvent", tags: new[] { "Post HistoryEvent" })]
[OpenApiSecurity("function_key", SecuritySchemeType.ApiKey, Name = "code", In = OpenApiSecurityLocationType.Query)]
[OpenApiRequestBody("application/json", typeof(HistoryEvent), Required = true, Description = "Description of OpenApiRequestBody", Example = typeof(HistoryEventOpenApiExample))]
[OpenApiResponseWithBody(statusCode: HttpStatusCode.Created, contentType: "application/json", bodyType: typeof(HistoryEvent), Description = "The created History Event")]
public async Task<IActionResult> PostHistoryEvent(...){...}
public class HistoryEventOpenApiExample : OpenApiExample<HistoryEvent>
{
public override IOpenApiExample<HistoryEvent> Build(NamingStrategy namingStrategy = null)
{
Examples.Add(OpenApiExampleResolver.Resolve(
"first",
new HistoryEvent()
{
ObjectId = "foo",
More properties ...
},
namingStrategy));
return this;
}
}
I assume I need to do add something, but I'm not sure what.
The reason you don't see examples in Swagger UI is likely that your Azure function is using OpenAPI 2.0 specification (aka Swagger 2.0). Setting OpenApiRequestBodyAttribute.Example
will only affect OpenAPI 3. For some reason, by default, Azure Functions OpenAPI Extension library is using OpenAPI 2.0.
There are two ways you can fix this.
OpenApiConfigurationOptions
If you already have a OpenApiConfigurationOptions
implementation class, then update OpenApiVersion
value to OpenApiVersionType.V3
. Otherwise, just create one.
It should look something like this:
public class OpenApiConfigurationOptions : DefaultOpenApiConfigurationOptions
{
public override OpenApiVersionType OpenApiVersion { get; set; } = OpenApiVersionType.V3;
// you can also update your API info as well here
// public override OpenApiInfo Info { get; set; } = new OpenApiInfo { ... };
}
OpenApiExample
attribute on a modelAdd the OpenApiExample
attribute to your data model that has a link to your HistoryEventOpenApiExample
class.
[OpenApiExample(typeof(HistoryEventOpenApiExample))]
public class HistoryEvent
{
public string ObjectId { get; set; }
// More properties ...
}