StackPractices
intermediate By Mathias Paulenko

HTTP-Triggered Azure Functions in Python

Create HTTP-triggered Azure Functions in Python with binding configuration, async handlers, dependency injection, and deployment via Azure CLI.

Overview

Azure Functions is Microsoft’s answer to AWS Lambda, and the Python v2 programming model finally makes it feel like Python. Gone are the per-function function.json files — you get decorators (@app.route, @app.cosmos_db_input, @app.service_bus_queue_trigger) registered from a single function_app.py. Squint and it looks like Flask.

This recipe builds an HTTP API the way you’d actually ship it — v2 triggers, Cosmos bindings that kill data-access boilerplate, async handlers, central error handling, env config, Azure CLI deploy. It also covers the hosting-plan side of cold starts, which is the difference between a hobby endpoint and a production API.

When to Use This

  • Building serverless HTTP APIs on Azure
  • Webhooks and event-driven HTTP endpoints
  • Lightweight microservices without managing infrastructure
  • Integrating with other Azure services (Cosmos DB, Service Bus, Storage)
  • Migrating a Flask/FastAPI-style API to serverless — the v2 model maps cleanly

Skip the Consumption plan for latency-sensitive APIs. It scales to zero, and every scale-up event costs a 1-5+ second cold start — users notice. Premium or an App Service plan keeps instances warm instead. Got a container-shaped workload with dependencies pip can’t express? Azure Container Apps is usually the better fit.

Prerequisites

  • Python 3.10+
  • Azure Functions Core Tools v4
  • Azure CLI
  • VS Code with Azure Functions extension (optional)

Solution

1. Create a Function App

# Install Azure Functions Core Tools
# macOS: brew tap azure/functions && brew install azure-functions-core-tools@4
# Windows: winget install Microsoft.AzureFunctionsCoreTools

# Create a new function app (v2 model)
func init MyFunctionApp --python
cd MyFunctionApp

# Add an HTTP-triggered function
func new --name HttpGetUser --template "HTTP trigger" --authlevel function

2. HTTP Trigger Function (v2 Model)

# function_app.py
import azure.functions as func
import json
import logging

app = func.FunctionApp()

@app.route(route="users/{user_id}", methods=["GET"])
def get_user(req: func.HttpRequest) -> func.HttpResponse:
    user_id = req.route_params.get('user_id')

    user = fetch_user_from_db(user_id)
    if not user:
        return func.HttpResponse(
            body=json.dumps({"error": "User not found"}),
            status_code=404,
            mimetype="application/json",
        )

    return func.HttpResponse(
        body=json.dumps(user),
        status_code=200,
        mimetype="application/json",
    )

@app.route(route="users", methods=["POST"])
def create_user(req: func.HttpRequest) -> func.HttpResponse:
    try:
        body = req.get_json()
    except ValueError:
        return func.HttpResponse(
            body=json.dumps({"error": "Invalid JSON"}),
            status_code=400,
            mimetype="application/json",
        )

    user = create_user_in_db(body)
    return func.HttpResponse(
        body=json.dumps(user),
        status_code=201,
        mimetype="application/json",
    )

The authlevel function flag from func new means requests need a ?code= key or x-functions-key header — right for production, annoying for local testing. Use --authlevel anonymous while developing locally.

3. Input/Output Bindings

import azure.functions as func
import json

app = func.FunctionApp()

# Cosmos DB input binding — fetch document by ID
@app.route(route="documents/{doc_id}")
@app.cosmos_db_input(
    arg_name="document",
    database_name="mydb",
    container_id="documents",
    id="{doc_id}",
    partition_key="{doc_id}",
    connection="CosmosDBConnection",
)
def get_document(req: func.HttpRequest, document: func.Document) -> func.HttpResponse:
    if document is None:
        return func.HttpResponse(
            body=json.dumps({"error": "Document not found"}),
            status_code=404,
            mimetype="application/json",
        )
    return func.HttpResponse(
        body=json.dumps(document.to_dict()),
        status_code=200,
        mimetype="application/json",
    )

# Cosmos DB output binding — save document
@app.route(route="documents", methods=["POST"])
@app.cosmos_db_output(
    arg_name="output",
    database_name="mydb",
    container_id="documents",
    connection="CosmosDBConnection",
)
def create_document(req: func.HttpRequest, output: func.Out[func.Document]) -> func.HttpResponse:
    body = req.get_json()
    output.set(func.Document.from_dict(body))
    return func.HttpResponse(
        body=json.dumps({"status": "created"}),
        status_code=201,
        mimetype="application/json",
    )

This is where Functions earns its keep. id="{doc_id}" wires the route parameter straight into a Cosmos lookup — no query string parsing, no client ceremony, the document just shows up as an argument.

The trigger above handles routes directly. Before async I/O, a few things worth knowing about how the worker runs your code: each Function App instance runs a Python worker process, and synchronous handlers block that worker for their whole duration — on a busy Consumption instance that’s your throughput ceiling. Async handlers let one worker interleave many requests while they wait on network or database calls.

4. Async Handlers

import azure.functions as func
import json
import aiohttp

app = func.FunctionApp()

@app.route(route="weather/{city}")
async def get_weather(req: func.HttpRequest) -> func.HttpResponse:
    city = req.route_params.get('city')
    api_key = req.params.get('api_key', 'default')

    async with aiohttp.ClientSession() as session:
        async with session.get(
            f"https://api.weather.example.com/{city}",
            headers={"X-API-Key": api_key},
        ) as response:
            data = await response.json()

    return func.HttpResponse(
        body=json.dumps(data),
        status_code=200,
        mimetype="application/json",
    )

5. Share a Service Instance

There’s no DI container in Functions — the working pattern is a module-level singleton, the same way you’d reuse a boto3 client in Lambda:

import azure.functions as func
import json
from dataclasses import dataclass

app = func.FunctionApp()

@dataclass
class UserService:
    db_connection_string: str

    def get_user(self, user_id: str) -> dict:
        # In production, use a real database client
        return {"id": user_id, "name": "Alice", "email": "alice@example.com"}

# Module-level: one instance per warm worker, reused across invocations
_user_service = UserService(db_connection_string="")

@app.route(route="users/{user_id}")
def get_user(req: func.HttpRequest) -> func.HttpResponse:
    user_id = req.route_params.get('user_id')
    user = _user_service.get_user(user_id)

    if not user:
        return func.HttpResponse(
            body=json.dumps({"error": "Not found"}),
            status_code=404,
            mimetype="application/json",
        )
    return func.HttpResponse(
        body=json.dumps(user),
        status_code=200,
        mimetype="application/json",
    )

6. Error Handling Middleware

import azure.functions as func
import json
import logging
import traceback
import functools

app = func.FunctionApp()

def handle_errors(fn):
    @functools.wraps(fn)
    async def wrapper(req: func.HttpRequest) -> func.HttpResponse:
        try:
            return await fn(req)
        except ValueError as e:
            logging.error(f"Validation error: {e}")
            return func.HttpResponse(
                body=json.dumps({"error": str(e)}),
                status_code=400,
                mimetype="application/json",
            )
        except Exception as e:
            logging.error(f"Unexpected error: {e}\n{traceback.format_exc()}")
            return func.HttpResponse(
                body=json.dumps({"error": "Internal server error"}),
                status_code=500,
                mimetype="application/json",
            )
    return wrapper

@app.route(route="orders", methods=["POST"])
@handle_errors
async def create_order(req: func.HttpRequest) -> func.HttpResponse:
    body = req.get_json()

    if not body.get("product_id"):
        raise ValueError("product_id is required")
    if not body.get("quantity") or body["quantity"] <= 0:
        raise ValueError("quantity must be positive")

    order = await process_order(body)
    return func.HttpResponse(
        body=json.dumps(order),
        status_code=201,
        mimetype="application/json",
    )

7. Configuration and Environment

// local.settings.json (development)
{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "CosmosDBConnection": "AccountEndpoint=https://...",
    "API_KEY": "dev-key-123"
  }
}

Access in code:

import os
import azure.functions as func

app = func.FunctionApp()

@app.route(route="config")
def get_config(req: func.HttpRequest) -> func.HttpResponse:
    api_key = os.environ.get("API_KEY", "not-set")
    cosmos_conn = os.environ.get("CosmosDBConnection", "not-set")

    return func.HttpResponse(
        body=json.dumps({
            "api_key_configured": api_key != "not-set",
            "cosmos_configured": cosmos_conn != "not-set",
        }),
        status_code=200,
        mimetype="application/json",
    )

local.settings.json never deploys and should stay out of git — production values live in the Function App’s Application Settings (or Key Vault references for secrets).

8. Deploy to Azure

# Create resource group
az group create --name my-rg --location eastus

# Create storage account (required by Functions)
az storage account create --name mystorageacct --resource-group my-rg --sku Standard_LRS

# Create the function app
az functionapp create \
  --name my-function-app \
  --resource-group my-rg \
  --storage-account mystorageacct \
  --runtime python \
  --runtime-version 3.11 \
  --functions-version 4 \
  --consumption-plan-location eastus

# Deploy
func azure functionapp publish my-function-app

On Premium and Dedicated plans, deploy to a staging slot and swap — it avoids users hitting a half-deployed app and warms the new code before traffic shifts. On Consumption there are no slots, so a publish is atomic enough for low traffic but plan a maintenance window for anything critical. Add --build remote to publish if your requirements.txt pulls native dependencies — remote build compiles them on Azure Linux instead of shipping your local wheels.

How It Works

  1. v2 programming model: @app.route() decorators instead of function.json files. function_app.py is the entry point, and Azure Functions picks up every decorated function on its own.
  2. Bindings: decorators do the plumbing — declare @app.cosmos_db_input and the document arrives as a parameter. No client code, no query, no connection string handling in the handler.
  3. Route parameters: {user_id} in the route comes back through req.route_params.get('user_id'). Query strings live in req.params.
  4. Async support: async def handlers run on the worker’s event loop. Reach for aiohttp and aiocosmos there — requests will block the loop and waste the whole point.
  5. Deployment: func azure functionapp publish zips and ships the project. On Consumption, the first request after idle pays a worker spin-up — that’s the cold start you saw in the Hosting Plans section.
flowchart diagram: REQ[

Hosting Plans

The plan decision drives cold starts, timeout, and cost more than anything in the code:

  • Consumption: pay-per-execution, scales to zero. Cold start of a few seconds on first hit after idle. Fine for webhooks and low-traffic APIs; painful for anything user-facing.
  • Premium (Elastic Premium): pre-warmed instances, VNet integration, longer timeouts. This is the default choice for production APIs — you pay for at least one warm instance (~$150/month for EP1) whether or not requests arrive.
  • Dedicated (App Service plan): same VM pricing as App Service, always-on, good when you already run one and want Functions to share its capacity.

Rule of thumb: prototype on Consumption, move to Premium when p95 latency matters or when monthly executions make the per-execution billing cost more than an EP1.

Variants

Timer-Triggered Function

Azure Functions uses NCRONTAB — six fields, seconds first (sec min hour day month dow):

import azure.functions as func
import logging

app = func.FunctionApp()

@app.schedule(schedule="0 0 */6 * * *", arg_name="timer", run_on_startup=False)
def cleanup_timer(timer: func.TimerRequest) -> None:
    logging.info(f"Timer triggered at: {timer.schedule_status}")
    # Run cleanup logic every 6 hours
    cleanup_expired_sessions()

A five-field Unix cron like 0 */6 * * * is a common copy-paste bug — it parses as seconds=0, minutes=*/6, hours=*… and fires every few seconds instead of every 6 hours.

Service Bus Queue Trigger

import azure.functions as func
import json

app = func.FunctionApp()

@app.service_bus_queue_trigger(
    arg_name="msg",
    queue_name="orders",
    connection="ServiceBusConnection",
)
def process_order_message(msg: func.ServiceBusMessage) -> None:
    order = json.loads(msg.get_body().decode('utf-8'))
    process_order(order)

Blob Storage Trigger

import azure.functions as func
import logging

app = func.FunctionApp()

@app.blob_trigger(
    arg_name="blob",
    path="uploads/{name}",
    connection="StorageConnection",
)
def process_upload(blob: func.InputStream) -> None:
    logging.info(f"Processing blob: {blob.name}, size: {blob.length} bytes")
    content = blob.read()
    process_file(content)

FastAPI Integration

If the API already exists as FastAPI, the azure-functions ASGI adapter runs it inside a function — you get FastAPI validation and OpenAPI docs while Functions handles scaling:

import azure.functions as func
from fastapi import FastAPI

fastapi_app = FastAPI()

@fastapi_app.get("/users/{user_id}")
def read_user(user_id: int):
    return {"user_id": user_id}

app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)

@app.route(route="{*route}", methods=["GET", "POST", "PUT", "DELETE"])
async def asgi_handler(req: func.HttpRequest) -> func.HttpResponse:
    return await func.AsgiMiddleware(fastapi_app).handle_async(req)

Best Practices

  • For the AWS side of the same problem, see Package Python Dependencies for AWS Lambda.
  • Stick with the v2 model: function.json is legacy — decorators are the supported path forward.
  • Use async for I/O-bound functions: Async handlers with aiohttp and async DB drivers improve throughput for I/O-bound workloads.
  • Keep handlers thin: push logic into service classes or module-level singletons; anything testable belongs outside the decorator.
  • Turn on Application Insights: one toggle in the portal buys you distributed tracing and error grouping — cheap insurance for a serverless API.
  • Set run_on_startup=False for timers: Otherwise the function runs on every deployment, which wastes resources.
  • Validate input yourself: Functions won’t reject a malformed body for you — Pydantic handles schema checks cleanly.

Common Mistakes

  • Blocking calls in async handlers: requests.get() blocks the event loop. Use aiohttp instead.
  • Five-field cron in timer triggers: Azure uses six-field NCRONTAB (0 0 */6 * * *), not Unix cron — a 5-field string silently schedules wrong.
  • Not handling JSON parse errors: req.get_json() raises ValueError on invalid JSON. Always wrap in try/except.
  • Using function.json with v2 model: The v2 model uses decorators. Mixing function.json and decorators causes conflicts.
  • Hardcoding connection strings: Use environment variables and App Settings. Never commit connection strings or local.settings.json.
  • Ignoring cold starts: The Consumption plan scales to zero and cold-starts on the next request. Premium plan pre-warms instances for latency-sensitive APIs.

Further Reading

Frequently Asked Questions

Azure Functions vs AWS Lambda — which should I choose?

If you're already on Azure (Cosmos DB, Service Bus, AD), Azure Functions integrates natively. If you're on AWS (DynamoDB, SQS, Cognito), Lambda is the natural choice. Both support Python and HTTP triggers.

What is the difference between Consumption and Premium plans?

Consumption scales to zero and charges per execution — but has cold starts. Premium pre-warms instances — no cold starts, but a fixed monthly cost per instance. Use Consumption for sporadic workloads, Premium for latency-sensitive APIs.

Can I use FastAPI with Azure Functions?

Yes — the ASGI middleware approach shown above wraps a FastAPI app inside a catch-all route. You keep FastAPI's validation and OpenAPI docs while Functions handles scaling.

How do I manage dependencies?

Create a requirements.txt file in the project root. Azure Functions installs dependencies during deployment. For native extensions, use a Docker container or a custom deployment image.

What is the maximum timeout for Azure Functions?

Consumption plan: 10 minutes (default 5). Premium/Dedicated plan: unlimited (configurable). For long-running tasks, use Durable Functions.

Where do secrets live in production?

In the Function App's Application Settings — ideally as Key Vault references (@Microsoft.KeyVault(...)) so secrets never sit in plain config. local.settings.json is development-only.