Monday, August 5, 2024

Azure APIM Wildcard Operations

I recently had a requirement where I wanted to expose some endpoints in an ASP.NET Core Web API via an Azure APIM, but those were not included in the APIs OpenAPI specification. These endpoints/operations were dynamically being added by a 3rd party library. 

With these operations not defined in the APIM, the consumers cannot reach the API/Backend. And I didn't want to add each of these 3rd party operations individually, and fortunately APIM supports Wildcard operations.

We can put wildcard operations by suffixing the URL with /*, something like below:
APIM: Add operation
This will route any GET operation under /reports/viewer/ to corresponding API/Backend.

And now I can't have these operations manually added to APIM, and wanted to add them into applications OpenAPI specification. I was using Swagger, so I can easily add a IDocumentFilter, something like the following.
public class DevExpressReportingDocumentFilter : IDocumentFilter
{
    public void Apply(OpenApiDocument openApiDocumentDocumentFilterContext context)
    {
        var reportViewerOperation = new OpenApiOperation
        {
            Summary = "Report Viewer",
            Tags =
            {
                new OpenApiTag { Name = "Reporting" }
            },
            Responses =
            {
                { "200"new OpenApiResponse() }
            }
        };

        var reportDesignerOperation = new OpenApiOperation
        {
            Summary = "Report Designer",
            Tags =
            {
                new OpenApiTag { Name = "Reporting" }
            },
            Responses =
            {
                { "200"new OpenApiResponse() }
            }
        };

        openApiDocument?.Paths.Add("/reports/viewer/*"new OpenApiPathItem()
        {
            Operations =
            {
                { OperationType.Get, reportViewerOperation },
                { OperationType.Post, reportViewerOperation }
            }
        });

        openApiDocument?.Paths.Add("/reports/designer/*"new OpenApiPathItem()
        {
            Operations =
            {
                { OperationType.Get, reportDesignerOperation },
                { OperationType.Post, reportDesignerOperation }
            }
        });
    }
}
And once these endpoints are available in OpenAPI specification, I can update the deployment of the API to import the OpenAPI specification to APIM which would result in something like this.
APIM: Wildcard Operations
Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment