Updating API management from Azure Devops Pipeline

by DotNetNerd 14. December 2022 12:32

Recently I needed to update Azure Management API based on the swagger specifications when our services were deployed. It seems like a pretty standard thing that there would be  a task for, but it turned out to require a bit of Powershell - it i still fairly simple though.

A general function to acccomplish it could look like this bit of code.


    [string] [Parameter(Mandatory=$true)] $ResourceGroupName,
    [string] [Parameter(Mandatory=$true)] $ServiceName,
    [string] [Parameter(Mandatory=$true)] $ApiName,
    [string] [Parameter(Mandatory=$true)] $SpecificationFilePath

$apiMgmtContext = New-AzApiManagementContext -ResourceGroupName $ResourceGroupName -ServiceName $ServiceName
$api = Get-AzApiManagementApi -Context $apiMgmtContext -ApiId $ApiName

if ($null -eq $api) {
    Write-Error "Failed to get API with name $ApiName"

$apiVersionSetId = $api.ApiVersionSetId.Substring($api.ApiVersionSetId.LastIndexOf("/")+1)
$apiVersionSet = Get-AzApiManagementApiVersionSet -Context $apiMgmtContext -ApiVersionSetId $apiVersionSetId

Import-AzApiManagementApi -Context $apiMgmtContext `
                        -SpecificationUrl $SpecificationFilePath `
                        -SpecificationFormat 'OpenApi' `
                        -Path $api.Path `
                        -ApiId $api.ApiId `
                        -ServiceUrl $api.ServiceUrl`
                        -ApiVersionSetId $apiVersionSet.Id




This can of course be used locally, but to run it from a release pipeline, the cleanest way I have found, is to add it to a separate repository, and include it as an artifact. From there we just need a Azure Powershell build step, configured as shown by the YAML below.


  swaggerUrl: 'https://my_appservice.azurewebsites.net/swagger/1.0.0/swagger.json'

- task: AzurePowerShell@5
  displayName: 'Azure PowerShell script: Update API Management'
    azureSubscription: 'xxx'
    ScriptPath: '$(System.DefaultWorkingDirectory)/_MyCompany.BuildScripts/UpdateApiManagement.ps1'
    ScriptArguments: '-ResourceGroupName "resource_group_name" -ServiceName "management_api_service_name" -ApiName "unique_api_id" -SpecificationFilePath $(swaggerUrl)'
    azurePowerShellVersion: LatestVersion


And that is all that is required, to automate it and make it update along with the build. Nice and easy.

Who am I?

My name is Christian Holm Diget, and I work as an independent consultant, in Denmark, where I write code, give advice on architecture and help with training. On the side I get to do a bit of speaking and help with miscellaneous community events.

Some of my primary focus areas are code quality, programming languages and using new technologies to provide value.

Microsoft Certified Professional Developer

Microsoft Most Valuable Professional

Month List

bedava tv izle