API Management (APIM) offers many features for consumers to use by providing a unified endpoint. In order to achieve this consolidation, importing existing API definitions is one of its key functionalities. APIM supports both document types in WADL and Swagger to import APIs. In this post, we’re going to discuss what we should know when dealing with Swagger documents.

The Issue

Importing Swagger document into APIM is pretty straight forward by following this Azure document. There’s no issue when you import Swagger 1.2 documents. However, if you’re intending to import Swagger 2.0 ones, you might be facing the screen like:

It gets stuck here forever with no indication. Your swagger.json file is all valid, by the way. What happens?

Findings

If you’re building an API app with .NET Framework 4.5+, using Swashbuckle library, it would be fine. However, if you’re building the app with ASP.NET Core, it does bring you a headache. Firstly, look at your Startup.cs file. The ConfigureService method looks like:

In addition to this, the Configure method might look like:

This is the basic settings for swagger for your Web API. Now run your API app and get the swagger.json document. It might look like:

Nothing seems to be wrong, right? This swagger.json file is even well validated, if you’re using another service like swaggerhub.com. How come this is not imported into APIM? Take a look at the modified swagger.json:

Can you identify what the differences are? You’re right. The modified one includes two additional properties – host and schemes. Swagger specification clearly declares that both are NOT required. However, APIM DOES require both properties to be included in the swagger.json document.

So, how can we sort this out?

Resolution

For your app in .NET 4.5+, just make sure that your SwaggerConfig.cs has activated those options with proper settings:

  • SwaggerDocsConfig.Schemes(new[] { “http”, “https” });
  • SwaggerDocsConfig.RootUrl(req => GetRootUrlFromAppConfig());

In your ASP.NET Core app, it might be tricky as you should implement the IDocumentFilter interface. Here’s a sample code:

And this SchemaDocumentFilter should be added into your ConfigureService method in Startup.cs:

Once you complete this, then import your swagger.json to APIM and viola! You’re now an APIM guru!

So far, we’ve had a brief look at an issue on APIM with swagger.json and its resolution. The sample code used in this post can be found at https://github.com/devkimchi/ASP.NET-Core-Tips-and-Tricks-Sample.

Happy coding!

Category:
Azure Platform, WebAPI
Tags:
,

Join the conversation! 5 Comments

  1. This helped me a lot. Thanks.

  2. But you are hard-coding the URL of the website. Do you know a way to provide the URL and schemes at runtime, and the base path from a config?

    • @Frankie Thanks for your comment! You can use appsettings.json to provide URL dynamically, like using web.config.

Comments are closed.