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-0.1.0.tar.gz (16.3 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-0.1.0.tar.gz.

File metadata

File hashes

Hashes for azure_functions_openapi_pydantic-0.1.0.tar.gz
Algorithm Hash digest
SHA256 6da243d3fe456b856269d116b31aa02aff9fb7cfecdf46034b90320776b7e94f
MD5 77bde6a7478a9a3da70100f154a9b7f3
BLAKE2b-256 ab8a8d09138494441dca021322012091bb9dccf7b123a4064e5ff066d3c4b4df

See more details on using hashes here.

File details

Details for the file azure_functions_openapi_pydantic-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for azure_functions_openapi_pydantic-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 fe114bbd4607719c7106ba9e80b39596c4e570478a5d4cf7b0f874b850c25bfd
MD5 c54c7170abc53894f2663308b5e0b5fd
BLAKE2b-256 8822a2250417488d827e7e8ea4f18cc4c731a51dce56cd500b928611f59c4aa6

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