Skip to main content

Call a weather API with a Key Vault secret

Deploy a Python weather dashboard whose server reads a WeatherAPI.com key from Azure Key Vault (a managed store for secrets) using managed identity.

Public development/test demo

Anyone who reaches the app can consume provider quota; in-process limits are not a spending cap. Use an isolated resource group, a dedicated provider key, and at most two hours.

Prerequisites​

  • An Azure subscription with permission to create Microsoft.Web/builderApps, a Key Vault, and role assignments, in West US 2 (westus2).
  • Git, Bash, Azure CLI with Bicep, GitHub CLI (gh), and the installed Builder CLI.
  • A GitHub account that can fork the sample and authorize the Builder GitHub App.
  • A private WeatherAPI.com key reserved for this exercise.
  • Public HTTPS from the app to the vault and api.weatherapi.com (Builder has no VNet integration or stable egress IPs).

See Key Vault pricing; the preview offer doesn't cover separately owned services.

1. Prepare your fork and resource values​

Fork the Key Vault weather sample, then define your subscription, tenant, new test group, globally unique vault name, app name, and fork:

SUBSCRIPTION="<subscription-id>"
TENANT="<tenant-id>"
RG="<new-test-resource-group>"
VAULT="<globally-unique-vault-name>"
APP="<new-builder-app-name>"
REPOSITORY="<your-github-owner>/<your-fork-name>"
BRANCH="main"

az login --tenant "$TENANT"
az account set --subscription "$SUBSCRIPTION"
gh auth login --hostname github.com
git clone "https://github.com/$REPOSITORY.git" key-vault-weather
cd key-vault-weather

OPERATOR_ID=$(az ad signed-in-user show --query id --output tsv)
az group create --subscription "$SUBSCRIPTION" \
--name "$RG" --location westus2

Before provisioning, install the App Service Builder GitHub App on your fork.

2. Provision settings and permissions before source​

Create a source-free app with its identity and approved expiry first, then save the vault connection before deploying source. A connection must select an already assigned identity with committed identifiers. From the sample root, create a local dependency/app template:

cat > tutorial-resources.bicep <<'BICEP'
param vaultName string
param appName string
param operatorPrincipalId string
param expiresAt string = dateTimeAdd(utcNow(), 'PT2H')

module provisionVault './infra/main.bicep' = {
name: 'weather-vault'
params: {
vaultName: vaultName
location: 'westus2'
}
}

resource vault 'Microsoft.KeyVault/vaults@2024-11-01' existing = {
name: vaultName
}

resource app 'Microsoft.Web/builderApps@2026-09-01-preview' = {
name: appName
location: 'westus2'
identity: {
type: 'SystemAssigned'
}
properties: {
versionConfiguration: {
variables: [
{
name: 'SAMPLE_EXPIRES_AT'
value: expiresAt
}
]
}
scaling: {
components: [
{
name: 'web'
minReplicas: 0
maxReplicas: 1
httpEnabled: true
}
]
}
}
}

resource visitorAccess 'Microsoft.Web/builderApps/authConfigs@2026-09-01-preview' = {
parent: app
name: 'default'
properties: {
mode: 'disabled'
}
}

resource appReader 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
name: guid(vault.id, app.id, 'weather-secret-reader')
scope: vault
properties: {
principalId: app.identity.principalId
principalType: 'ServicePrincipal'
roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '4633458b-17de-408a-b874-0445c86b69e6')
}
}

resource operatorWriter 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
name: guid(vault.id, operatorPrincipalId, 'weather-secret-operator')
scope: vault
properties: {
principalId: operatorPrincipalId
principalType: 'User'
roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'b86a8fe4-44ce-4948-aee5-eccb2c155cd7')
}
dependsOn: [
provisionVault
]
}

output vaultUrl string = provisionVault.outputs.vaultUrl
output appPrincipalId string = app.identity.principalId
output sampleExpiresAt string = expiresAt
output readerRoleAssignmentId string = appReader.id
output operatorRoleAssignmentId string = operatorWriter.id
BICEP

az deployment group what-if --subscription "$SUBSCRIPTION" \
--resource-group "$RG" --name weather-resources \
--template-file tutorial-resources.bicep \
--parameters vaultName="$VAULT" appName="$APP" operatorPrincipalId="$OPERATOR_ID"

Review the changes, then create the resources:

az deployment group create --subscription "$SUBSCRIPTION" \
--resource-group "$RG" --name weather-resources \
--template-file tutorial-resources.bicep \
--parameters vaultName="$VAULT" appName="$APP" operatorPrincipalId="$OPERATOR_ID"

az deployment group show --subscription "$SUBSCRIPTION" \
--resource-group "$RG" --name weather-resources \
--query properties.outputs --output json

Record sampleExpiresAt (two hours out; don't rerun provisioning to extend it) and keep the template out of the source branch. Secrets User lets the app read secrets in this vault only; Secrets Officer lets your operator enter the secret. Role propagation can take time.

3. Enter the credential directly in Key Vault​

The weather key stays on the server
  1. Browser requests weather

    The page sends a location to the app. It does not receive a vault secret or a weather-provider key.

  2. App identity reads Key Vault

    Server code uses the app's system identity to retrieve the named secret. The vault independently enforces the app's secret-read permission.

  3. Server calls WeatherAPI

    The server uses the protected provider key and returns bounded weather data. The page labels fresh or cached results and displays the selected units.

The Key Vault connection supplies runtime configuration; app code retrieves the secret. Saving a connection is not secret retrieval, and opening a configured weather page can consume provider quota.
  1. Open your new vault in Azure Portal.
  2. Select Objects > Secrets > Generate/Import and choose manual entry.
  3. Name the secret weather-api-key and enter the dedicated WeatherAPI key directly in the secret-value field.
  4. Enable the secret and set its expiration to the recorded sampleExpiresAt.
  5. Select Create.

Never put the API key in a shell command, Git, Builder variables, or screenshots.

In Builder Portal, confirm Identity shows the committed system-assigned identity and Scaling is 0–1. Keep only SAMPLE_EXPIRES_AT in Variables; leave AZURE_CLIENT_ID and AZURE_AUTH_MODE unset and never store the provider key there.

Save the vault connection​

An updated target's Key Vault connection profile records routing metadata, not the WeatherAPI credential. Select the existing vault and already-assigned app identity, then map vaultUri to this sample's KEY_VAULT_URL and secretName to KEY_VAULT_SECRET_NAME. Do not leave the suggested KEY_VAULT_URI name unchanged: this sample reads KEY_VAULT_URL. Avoid duplicate manual entries for those exact names; retain SAMPLE_EXPIRES_AT as a separate app variable. The existing Secrets User grant and SDK code still retrieve the secret from Key Vault. Builder does not resolve a keyVaultReference, move the provider key into its Variables store, or grant access merely by saving mappings. The deployed catalog advertises this profile; named sample delivery still needs its own deployed vault/weather verification, separate from historical direct-variable proof. Use the Builder CLI procedure with a release that includes app connections, or Azure CLI/ARM, with the same complete keyVault object. Saving the connection does not deploy source, create the provider secret or authorize its read.

4. Connect and deploy the selected source​

Sign in to Builder and GitHub source:

builder login
builder account show
builder source login github
REPOSITORY_ID=$(gh api --hostname github.com "repos/$REPOSITORY" --jq '.id')

builder app source connect github --name "$APP" \
--subscription "$SUBSCRIPTION" --resource-group "$RG" \
--repository "$REPOSITORY" --repository-id "$REPOSITORY_ID" --branch "$BRANCH"

Complete the browser sign-in with the GitHub account that can access the fork; if source access isn't confirmed, finish the GitHub App installation and retry.

builder app deploy --name "$APP" \
--subscription "$SUBSCRIPTION" --resource-group "$RG"
builder app show --name "$APP" \
--subscription "$SUBSCRIPTION" --resource-group "$RG"

If the wait fails, check the existing deployment before resubmitting. Confirm the revision in Versions; /health doesn't prove Key Vault access.

5. Verify weather, location entry, and units​

APP_URL="<returned-app-runtime-url>"
curl --fail --silent --show-error "$APP_URL/health"
curl --fail --silent --show-error "$APP_URL/api/weather/seattle"
curl --fail --silent --show-error "$APP_URL/api/weather/seattle"
curl --fail --silent --show-error --get "$APP_URL/api/weather" \
--data-urlencode "location=Paris"

The weather response must contain observations, observedAt, fetchedAt, and cached, with no credential field; the repeated Seattle request should return "cached":true. Only a real weather response proves managed-identity secret retrieval.

In the dashboard, try a quick pick, a city or postal code (such as Paris or SW1A 1AA), and the Units toggle. If weather is unavailable, check the secret and its expiry, app identity, vault permission, and network access.

Use the pattern in your own app​

The same pattern works for any non-Entra API credential. Never put the value in Git, Builder variables, or frontend assets. Give the app's identity Key Vault Secrets User only (never Officer, Contributor, or Owner), map KEY_VAULT_URL and KEY_VAULT_SECRET_NAME in Connections, and read the secret server-side with the Azure SDK (see Key Vault RBAC):

import os
from datetime import datetime, timezone
from azure.core.exceptions import AzureError
from azure.identity import ManagedIdentityCredential
from azure.keyvault.secrets import SecretClient

client = SecretClient(
os.environ["KEY_VAULT_URL"],
ManagedIdentityCredential(),
retry_total=0,
connection_timeout=3,
read_timeout=5,
)

def read_api_credential():
try:
secret = client.get_secret(
os.environ["KEY_VAULT_SECRET_NAME"], logging_enable=False
)
except AzureError:
raise RuntimeError("Cannot read the configured API credential.") from None
if secret.properties.enabled is False or not secret.value:
raise RuntimeError("The configured API credential is unavailable.")
expiry = secret.properties.expires_on
if expiry and expiry <= datetime.now(timezone.utc):
raise RuntimeError("The configured API credential has expired.")
return secret.value
  • Call a fixed HTTPS destination with timeouts and size limits, never a visitor-supplied URL.
  • Return only needed data and sanitized errors; keep request URLs and exceptions out of logs.
  • Cache only until before the secret's expiry, within Key Vault limits.
  • An expired or disabled secret must fail, not fall back to an app setting.
  • Builder has no VNet integration or stable outbound IPs; HTTPS reachability to the vault is required.
  • A healthy deployment doesn't prove vault access; a local az login doesn't verify the hosted identity.

Cache, quota, and rotation behavior​

Weather is cached ten minutes per query (up to 64 observations and 64 failures per process). Up to 12 uncached entered-place lookups are accepted per rolling minute, and all provider attempts share a 500-attempt UTC-day process limit; restarts and scaling can increase usage. These aren't account-wide quotas.

The secret is cached up to five minutes, never past its expiry. To rotate, create a new secret version; cached weather can remain ten minutes, so rotation isn't instant revocation. A provider authentication failure starts a one-minute cooldown, and no provider call starts at or after SAMPLE_EXPIRES_AT.

Clean up resources​

Confirm the group contains only this exercise's app and vault:

az resource list --subscription "$SUBSCRIPTION" \
--resource-group "$RG" --query "[].{name:name,type:type}" --output table

READER_ROLE_ID=$(az deployment group show --subscription "$SUBSCRIPTION" \
--resource-group "$RG" --name weather-resources \
--query properties.outputs.readerRoleAssignmentId.value --output tsv)
OPERATOR_ROLE_ID=$(az deployment group show --subscription "$SUBSCRIPTION" \
--resource-group "$RG" --name weather-resources \
--query properties.outputs.operatorRoleAssignmentId.value --output tsv)

builder app delete --name "$APP" \
--subscription "$SUBSCRIPTION" --resource-group "$RG"
az role assignment delete --subscription "$SUBSCRIPTION" \
--ids "$READER_ROLE_ID" "$OPERATOR_ROLE_ID"
az group delete --subscription "$SUBSCRIPTION" --name "$RG"
az group exists --subscription "$SUBSCRIPTION" --name "$RG"

Confirm the deletion prompts and wait until the az group exists check must return false. Soft deletion retains the vault for seven days; don't purge it. Azure deletion doesn't revoke the provider key; revoke it yourself.