Skip to main content

OpenAPI (Swagger) integration for Python-based Azure Functions

Project description

azure-functions-openapi

PyPI Python Version CI codecov pre-commit Docs License: MIT

Effortless OpenAPI (Swagger) documentation & Swagger‑UI for Python Azure Functions.


Features

Core Features

  • @openapi decorator — annotate once, generate full spec
  • Serves /openapi.json, /openapi.yaml, and /docs (Swagger UI)
  • Supports query/path/header parameters, requestBody, responses, tags
  • Optional Pydantic integration (supports both v1 and v2)
  • Zero hard dependency on Pydantic

Security & Performance

  • Enhanced Security: CSP headers, input validation, XSS protection
  • Performance Caching: In-memory caching with TTL and LRU eviction
  • Error Handling: Standardized error responses with detailed logging
  • Input Sanitization: Automatic sanitization of routes, operation IDs, and parameters

Monitoring & Operations

  • Health Checks: Built-in health monitoring for all components
  • Performance Metrics: Response time tracking, throughput monitoring
  • Request Logging: Detailed request/response logging with statistics
  • Server Information: Comprehensive server info and runtime details

Developer Experience

  • CLI Tool: Command-line interface for spec generation, validation, and monitoring
  • Comprehensive Testing: 97% test coverage with extensive test suites
  • Documentation: Detailed guides for security, performance, and CLI usage
  • Type Safety: Full type hints and validation throughout

Installation

pip install azure-functions-openapi

For local development:

git clone https://github.com/yeongseon/azure-functions-openapi.git
cd azure-functions-openapi
pip install -e .[dev]

Quick Start

Create a minimal HTTP-triggered Azure Function with auto Swagger documentation.

  1. Set up environment
python -m venv .venv
source .venv/bin/activate
pip install azure-functions azure-functions-worker azure-functions-openapi
  1. Initialize Azure Functions project
func init hello_openapi --python
cd hello_openapi
  1. Add function_app.py with OpenAPI-decorated function and endpoints:
# hello_openapi/function_app.py

import json
import azure.functions as func
from azure_functions_openapi.decorator import openapi
from azure_functions_openapi.openapi import get_openapi_json, get_openapi_yaml
from azure_functions_openapi.swagger_ui import render_swagger_ui

app = func.FunctionApp()

@openapi(
    summary="Greet user",
    route="/api/http_trigger",
    request_model={"name": "string"},
    response_model={"message": "string"},
    tags=["Example"]
)
@app.function_name(name="http_trigger")
@app.route(route="/api/http_trigger", auth_level=func.AuthLevel.ANONYMOUS, methods=["POST"])
def main(req: func.HttpRequest) -> func.HttpResponse:
    try:
        data = req.get_json()
        name = data.get("name", "world")
        return func.HttpResponse(
            json.dumps({"message": f"Hello, {name}!"}),
            mimetype="application/json"
        )
    except Exception as e:
        return func.HttpResponse(f"Error: {str(e)}", status_code=400)

@app.function_name(name="openapi_json")
@app.route(route="/api/openapi.json", auth_level=func.AuthLevel.ANONYMOUS, methods=["GET"])
def openapi_json(req: func.HttpRequest) -> func.HttpResponse:
    return get_openapi_json()

@app.function_name(name="openapi_yaml")
@app.route(route="/api/openapi.yaml", auth_level=func.AuthLevel.ANONYMOUS, methods=["GET"])
def openapi_yaml(req: func.HttpRequest) -> func.HttpResponse:
    return get_openapi_yaml()

@app.function_name(name="swagger_ui")
@app.route(route="/api/docs", auth_level=func.AuthLevel.ANONYMOUS, methods=["GET"])
def swagger_ui(req: func.HttpRequest) -> func.HttpResponse:
    return render_swagger_ui()

Swagger UI (/docs) is now supported via render_swagger_ui() helper.

  1. Run locally:
func start
  1. Deploy:
func azure functionapp publish <FUNCTION-APP-NAME> --python
  • OpenAPI JSON: https://.azurewebsites.net/api/openapi.json

A partial example of the generated /api/openapi.json:

{
  "openapi": "3.0.0",
  "info": {
    "title": "API",
    "version": "1.0.0",
    "description": "Auto-generated OpenAPI documentation. Markdown supported in descriptions (CommonMark)."
  },
  "paths": {
    "/api/http_trigger": {
      "get": {
        "summary": "HTTP Trigger with name parameter",
        "description": "Returns a greeting using the **name** from query or body.",
        "parameters": [
          {
            "name": "name",
            "in": "query",
            "required": true,
            "schema": { "type": "string" },
            "description": "Name to greet"
          }
        ],
        "responses": {
          "200": {
            "description": "Successful response with greeting",
            "content": {
              "application/json": {
                "examples": {
                  "sample": {
                    "summary": "Example greeting",
                    "value": {
                      "message": "Hello, Azure!"
                    }
                  }
                }
              }
            }
          },
          "400": { "description": "Invalid request" }
        }
      }
    }
  }
}
  • Swagger UI: https://.azurewebsites.net/api/docs

Swagger UI will look once you set up the routes:

Swagger UI Example


Example with Pydantic

from pydantic import BaseModel
from azure_functions_openapi.decorator import openapi

class RequestModel(BaseModel):
    name: str

class ResponseModel(BaseModel):
    message: str

@openapi(
    summary="Greet user (Pydantic)",
    route="/api/http_trigger",
    request_model=RequestModel,
    response_model=ResponseModel,
    tags=["Example"]
)
def http_trigger(req: func.HttpRequest) -> func.HttpResponse:
    ...

Supports both Pydantic v1 and v2. Schema inference will work automatically with either version.


CLI Tool

The package includes a powerful CLI tool for various operations:

# Generate OpenAPI specification
azure-functions-openapi generate --title "My API" --version "1.0.0"

# Get server information
azure-functions-openapi info

# Check health status
azure-functions-openapi health

# Get performance metrics
azure-functions-openapi metrics

# Validate OpenAPI specification
azure-functions-openapi validate openapi.json

See CLI Guide for complete documentation.

Documentation


License

MIT © 2025 Yeongseon Choe

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

azure_functions_openapi-0.6.0.tar.gz (177.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

azure_functions_openapi-0.6.0-py3-none-any.whl (25.7 kB view details)

Uploaded Python 3

File details

Details for the file azure_functions_openapi-0.6.0.tar.gz.

File metadata

  • Download URL: azure_functions_openapi-0.6.0.tar.gz
  • Upload date:
  • Size: 177.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.12

File hashes

Hashes for azure_functions_openapi-0.6.0.tar.gz
Algorithm Hash digest
SHA256 b0e18f5ac7a77fa03006c7de02f1246cbb458dbeb122ac56428d873ba37fa4da
MD5 a0ab9a37a0f5a9f4862302b734dd2263
BLAKE2b-256 8c906aca13cd9bb43cb3b9ef976622b9abff6acba2afafbe45b6dde32ceda36a

See more details on using hashes here.

File details

Details for the file azure_functions_openapi-0.6.0-py3-none-any.whl.

File metadata

File hashes

Hashes for azure_functions_openapi-0.6.0-py3-none-any.whl
Algorithm Hash digest
SHA256 6f2dd9a9706e8f117563f6990ec6261d6534a8e2a3cc177db37e90ca4c6d0827
MD5 7c464d6ccffa8efdb8a224b408f7a80a
BLAKE2b-256 212f3dbe762aa85b85608d0e31c40e29b6f0476b6737210ec4e60ca5118e4633

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page