Skip to content

Configuration

This guide covers configuration points across:

  • @openapi decorator parameters
  • OpenAPI version selection (3.0.0 vs 3.1.0)
  • spec generation options
  • Swagger UI rendering options
  • security scheme setup

@openapi parameters

@openapi(...) is the primary configuration surface.

Metadata fields

Parameter Type Purpose
summary str Short operation summary in Swagger UI
description str Long operation description (Markdown supported)
tags list[str] \| None Group operations in docs; defaults to ['default']
operation_id str \| None Custom operation ID; sanitized to safe identifier

Routing and protocol fields

Parameter Type Purpose
route str \| None Override documented path (for example /api/items/{id})
method str \| None Force HTTP method used in spec (get, post, etc.)
parameters list[dict] \| None OpenAPI Parameter Objects for path/query/header/cookie

Security fields

Parameter Type Purpose
security list[dict[str, list[str]]] \| None Operation-level security requirements
security_scheme dict[str, dict] \| None Security schemes merged into components.securitySchemes

Body and response fields

Prefer the unified requests / responses parameters. Each accepts either a Pydantic model class or a raw schema dict.

Parameter Type Purpose
requests type[BaseModel] \| dict \| None Unified request body — model (like request_model) or raw schema dict (like request_body)
request_body_required bool Whether the request body is required; defaults to True
responses type[BaseModel] \| dict[int, dict] \| None Unified responses — model (typed 200 schema) or a status-code map (like response)

Removed from @openapi (issue #285)

These discrete parameters were removed from @openapi. Use the unified requests / responses parameters instead. They remain available on register_openapi_metadata() for programmatic registration.

Removed parameter Type Replacement
request_model type[BaseModel] \| None requests=Model
request_body dict \| None requests={...}
response_model type[BaseModel] \| None responses=Model
response dict[int, dict] \| None responses={...}

Warning

A model passed to requests / responses must be a Pydantic BaseModel class; pass a dict for raw schemas.

Typed success body plus extra status codes

A model-derived success schema and extra status codes are expressed with a single responses= map: give each status either a Pydantic model or an explicit Response Object (with content.schema). See the migration guide.

Parameter examples

Metadata and route

@openapi(
    summary="Get product",
    description="Returns one product by id.",
    tags=["Products"],
    operation_id="getProduct",
    route="/api/products/{id}",
    method="get",
)

Parameters

@openapi(
    summary="Get product",
    method="get",
    parameters=[
        {
            "name": "id",
            "in": "path",
            "required": True,
            "schema": {"type": "integer"},
        },
        {
            "name": "locale",
            "in": "query",
            "required": False,
            "schema": {"type": "string", "default": "en-US"},
        },
    ],
)

Route inline constraints

Azure route templates may constrain a segment inline. A constrained segment is normalized into the OpenAPI path plus a required path parameter, because OpenAPI matches a template variable to a parameter by name — leaving {id:int} in the path would describe a different endpoint than the one the runtime serves.

@openapi(summary="Get item", method="get", route="items/{id:int}")

produces the path /api/items/{id} and this parameter:

{ "name": "id", "in": "path", "required": true, "schema": { "type": "integer" } }

The supported Azure route-template subset is:

  • literal segments, including dotted static segments such as v1.0/items
  • required variables such as {id}
  • required int and alpha constraints
constraint schema notes
:int {"type": "integer"}
:alpha {"type": "string"} No pattern is emitted. alpha constrains Azure's routing, not the value's format, so a pattern would assert a payload contract the runtime does not enforce.

All other Azure route-template syntax is unsupported. This includes optional parameters ({id?}, {id:int?}), catch-all parameters ({*rest}), and every other constraint, including guid, bool, datetime, long, float, double, decimal, min, max, range, length, minlength, maxlength, and regex(...). These forms are rejected instead of being weakened to a required plain string.

An authored route that is visible to @openapi raises ValueError immediately. If the route is resolved later from a scanned FunctionApp binding, strict=True raises during generation; non-strict generation follows the existing malformed-operation convention by skipping that operation and recording an operation-skipped structured warning.

Precedence. An explicit parameters entry always wins. If it declares a schema that disagrees with the route constraint, the explicit schema is kept and the disagreement is reported — as a warning normally, and as an error under strict=True. An explicit entry with no schema adopts the constraint's.

Request/response models

Explicit model conversion failures are operation-attributed. With strict=True, generation raises and preserves the conversion exception as the cause; the error identifies the method, normalized emitted path (including the configured route prefix), function or registry identity, and whether the failure occurred in the request body or a response status. In non-strict mode, generation keeps the existing generic-schema/default-response fallback and records a schema-substitution SpecWarning whose optional method, path, and location fields carry the same context.

class ProductCreate(BaseModel):
    name: str


class ProductResponse(BaseModel):
    id: int
    name: str


# Single typed response — fully migratable to the unified parameters:
@openapi(
    summary="Create product",
    method="post",
    requests=ProductCreate,
    responses=ProductResponse,
)


# Model-derived 200 plus extra status codes — one unified `responses=` map:
@openapi(
    summary="Create product",
    method="post",
    requests=ProductCreate,
    responses={
        201: {
            "description": "Created",
            "content": {"application/json": {"schema": ProductResponse}},
        },
        400: {"description": "Bad request"},
    },
)

OpenAPI version selection

Supported versions:

  • OPENAPI_VERSION_3_0 ("3.0.0")
  • OPENAPI_VERSION_3_1 ("3.1.0")
  • OPENAPI_VERSION_3_2 ("3.2.0")
from azure_functions_openapi import OPENAPI_VERSION_3_1, get_openapi_json

json_spec = get_openapi_json(
    title="Catalog API",
    version="2026.03",
    openapi_version=OPENAPI_VERSION_3_1,
)

What changes in 3.1 / 3.2 mode

  • nullable schemas are converted from nullable: true to type: [<type>, "null"]
  • example values are normalized to examples

3.2.0 is a backward-compatible superset of 3.1.0 and reuses the same JSON Schema 2020-12 conversions. This library emits a valid 3.2.0 document and supports 3.2-only constructs (the querystring parameter — see below — non-standard HTTP methods via additionalOperations, the query HTTP method, and streaming media types via itemSchema). Note that some viewers — including the bundled Swagger UI — may not yet render 3.2.0 documents.

Querystring parameters (3.2 only)

OpenAPI 3.2 introduces the querystring parameter location, which describes the entire query string as a single schema-backed value instead of enumerating individual query parameters. Pass a Pydantic model or a raw JSON Schema dict via querystring=:

from pydantic import BaseModel

class SearchQuery(BaseModel):
    q: str
    limit: int = 10

@openapi(
    method="get",
    querystring=SearchQuery,
    # querystring_media_type defaults to application/x-www-form-urlencoded
)
@app.route(route="search", methods=["GET"])
def search(req):
    ...

This emits a single in: querystring parameter whose content schema is derived from the model. Constraints enforced at generation time:

  • querystring is only valid when openapi_version="3.2.0"; using it under 3.0/3.1 raises OpenAPISpecConfigError.
  • An operation may declare at most one querystring parameter.
  • A querystring parameter must not coexist with any in: query parameter in the same operation.

The raw parameters=[{"in": "querystring", "content": {...}}] escape hatch is also supported for callers who need full control over the media type or schema.

Spec generation options

generate_openapi_spec(...)

Use this when you need an in-memory dict:

spec = generate_openapi_spec(
    title="Catalog API",
    version="2026.03",
    description="Catalog service",
    security_schemes={
        "BearerAuth": {"type": "http", "scheme": "bearer", "bearerFormat": "JWT"}
    },
)

get_openapi_json(...) and get_openapi_yaml(...)

Use these for endpoint responses or file output:

json_text = get_openapi_json(title="Catalog API", version="2026.03")
yaml_text = get_openapi_yaml(title="Catalog API", version="2026.03")

Note

Both functions return strings. Create func.HttpResponse yourself when serving them from Azure Functions routes.

Swagger UI customization

render_swagger_ui(...) parameters:

Parameter Type Default Description
title str API Documentation Browser tab title
openapi_url str /api/openapi.json URL to the OpenAPI endpoint
custom_csp str \| None None Replace default Content Security Policy
enable_client_logging bool False Log API responses in browser console

Example:

return render_swagger_ui(
    title="Catalog API Docs",
    openapi_url="/api/openapi.json",
    enable_client_logging=True,
)

Custom CSP example:

custom_csp = "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net"
return render_swagger_ui(custom_csp=custom_csp)

Security scheme configuration

You can define schemes in two places.

Per-operation in decorator

@openapi(
    summary="Get profile",
    method="get",
    security=[{"BearerAuth": []}],
    security_scheme={
        "BearerAuth": {
            "type": "http",
            "scheme": "bearer",
            "bearerFormat": "JWT",
        }
    },
)

Global in spec generator

global_schemes = {
    "ApiKeyAuth": {"type": "apiKey", "in": "header", "name": "X-API-Key"}
}

json_spec = get_openapi_json(security_schemes=global_schemes)

The generated spec merges global and decorator-defined schemes into components.securitySchemes.

Validation and safety rules

The library validates and sanitizes:

  • route paths (validate_route_path)
  • operation IDs (sanitize_operation_id)
  • parameter shape (name and in required)
  • security requirement object types

Invalid values raise ValueError during decorator registration.