Microsoft Azure App Service can not only be used to host web apps but they can also be used to host API services. Swagger is a framework for describing your API using a common language that everyone can understand. In order for the other softwares to parse your Swagger and notice your API as connector, it’s necessary that you enable CORS and set the APIDefinition properties of the web application you want to use:
In this blog post, we’ll learn how to achieve the same using Azure ARM template. First, let’s add a CORS setting which is usually set to *. However, this can easily be set to any specific endpoint starting with either http or https. To add CORS setting, we would need to add below code into siteconfig object inside web app properties:
"cors": { "allowedOrigins": [ "*" ] }
Since we mentioned an array in the above code, we can mention many urls at same time.
Similarly, we can set API definition in the form of below code into siteconfig object:
"apiDefinition": { "url": "[concat('https://', reference(concat('Microsoft.Web/sites/', variables('webAppNameVar'))).defaultHostName, '/swagger/docs/v1')]" }
In above post, we set apiDefinition by concatenating first https, then Micorosft.Web/Sites followed by webapp/apiapp url and finally /swagger/docs/v1 url. This makes our property dynamic enough.
So that our Azure ARM template looks like below:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Adds Web Site | |
{ | |
"name": "[variables('webAppNameVar')]", | |
"type": "Microsoft.Web/sites", | |
"location": "[resourceGroup().location]", | |
"apiVersion": "2015-08-01", | |
"kind": "apiApp", | |
"dependsOn": [ | |
"[resourceId('Microsoft.Web/serverfarms', parameters('appHostingPlanName'))]" | |
], | |
"properties": { | |
"name": "[variables('webAppNameVar')]", | |
"serverFarmId": "[variables('appHostingPlanIdVar')]", | |
"siteConfig": { | |
"AlwaysOn": true, | |
"apiDefinition": { | |
"url": "[concat('https://', reference(concat('Microsoft.Web/sites/', variables('webAppNameVar'))).defaultHostName, '/swagger/docs/v1')]" | |
}, | |
"cors": { | |
"allowedOrigins": [ | |
"*" | |
] | |
} | |
} | |
} |
A reference for all web properties can be found here: https://docs.microsoft.com/en-us/azure/templates/microsoft.web/sites