Skip to main content

Lightweight OpenAPI decorator for Azure Functions with Pydantic support

Project description

Azure Functions OpenAPI with Pydantic

A lightweight, modern OpenAPI decorator for Azure Functions with full Pydantic support. Generate accurate API documentation with minimal code.

Features

  • 🎯 Simple decorator syntax - Just add @openapi() to your functions
  • 📝 Pydantic integration - Define request/response models with validation
  • 🔄 Response envelope - Standardized {success, data, error} format
  • 🏗️ Nested models - Automatically expands nested Pydantic models in docs
  • Blueprint support - Works seamlessly with Azure Functions blueprints
  • 📊 Smart defaults - Auto-generates HTTP status codes based on your endpoint

Installation

pip install azure-functions-openapi-pydantic

Quick Start

from azure.functions import HttpRequest, HttpResponse, Blueprint
from pydantic import BaseModel, Field, EmailStr
from azfunc_openapi_pydantic import openapi, ApiResponse, OpenAPIBlueprint

# Define your models
class CreateUserRequest(BaseModel):
    name: str = Field(..., min_length=1, max_length=100)
    email: EmailStr

class User(BaseModel):
    id: str
    name: str
    email: EmailStr
    created_at: str

# Create blueprint with OpenAPI support
api_bp = OpenAPIBlueprint()

# Decorate your function
@api_bp.route(route="users", methods=["POST"])
@openapi(request=CreateUserRequest, response=User)
def create_user(req: HttpRequest) -> HttpResponse:
    """Create a new user"""
    body = req.validated_body  # Validated Pydantic model attached by decorator
    
    user = User(
        id="usr_123",
        name=body.name,
        email=body.email,
        created_at="2025-01-01T00:00:00Z"
    )
    
    return ApiResponse.ok(user, status_code=201)

Generate OpenAPI Spec & Docs

from azfunc_openapi_pydantic import generate_openapi_spec, generate_swagger_ui
import json

@app.route(route="openapi.json", methods=["GET"])
def openapi_spec(req: HttpRequest) -> HttpResponse:
    spec = generate_openapi_spec(title="My API", version="1.0.0")
    return HttpResponse(json.dumps(spec, indent=2), mimetype="application/json")

@app.route(route="docs", methods=["GET"])
def swagger_ui(req: HttpRequest) -> HttpResponse:
    return generate_swagger_ui(title="My API Documentation")

Response Envelope

All responses follow a consistent envelope format:

Success:

{
  "success": true,
  "data": { /* your response model */ },
  "error": null
}

Error:

{
  "success": false,
  "data": null,
  "error": "Error message"
}

Decorator Options

@openapi(
    request=RequestModel,      # Pydantic model for POST/PUT body
    response=ResponseModel,    # Pydantic model for response data
    params={"id": str},        # Query/path parameters
    tags=["Users"],            # OpenAPI tags
    summary="Custom summary",  # Override function docstring
    errors={404: "Not found"}  # Custom error responses
)

Nested Models

Nested Pydantic models are automatically expanded in the OpenAPI spec:

class Address(BaseModel):
    street: str
    city: str
    country: str = "US"

class UserProfile(BaseModel):
    user: User
    address: Address
    preferences: dict

@openapi(response=UserProfile)
def get_profile() -> HttpResponse:
    # OpenAPI spec will show full nested structure
    ...

Examples

Check out the examples/ directory for a complete working Azure Functions app demonstrating:

  • Full CRUD operations
  • Request validation and error handling
  • Nested models and complex data structures
  • Pagination and query parameters
  • OpenAPI spec generation
  • Swagger UI integration

To run the example:

cd examples
pip install -r requirements.txt
func start

Then visit http://localhost:7071/api/docs for interactive API documentation.

License

MIT

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_pydantic-1.0.0a1.tar.gz (16.5 kB view details)

Uploaded Source

Built Distribution

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

File details

Details for the file azure_functions_openapi_pydantic-1.0.0a1.tar.gz.

File metadata

File hashes

Hashes for azure_functions_openapi_pydantic-1.0.0a1.tar.gz
Algorithm Hash digest
SHA256 4df9e31a5f5ef550af33c2dc8f804bd1a089e580731bd1ba2b3814c72ffcbdb8
MD5 df9ff191450d1cea0fa67c2702cc9e42
BLAKE2b-256 3b5385e262ccfeeb23552c54b93077df36f7903644a9915f58ef58bb759196fa

See more details on using hashes here.

File details

Details for the file azure_functions_openapi_pydantic-1.0.0a1-py3-none-any.whl.

File metadata

File hashes

Hashes for azure_functions_openapi_pydantic-1.0.0a1-py3-none-any.whl
Algorithm Hash digest
SHA256 3929ee1263b68fd043022f552d4d4b06204cf72adcfa63bca0359028ad6b05b3
MD5 60a5e0b36bef9435739830396698dbd5
BLAKE2b-256 a33108181fe64fbdb71f7e6dec5740752dedefc7973b5a23d3a4159e8c198405

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