Skip to content

API Reference

This page documents the public runtime API exposed by azure-functions-openapi.

Import from package root

All symbols below are exported from azure_functions_openapi.__init__, so you can import from azure_functions_openapi directly.

from azure_functions_openapi import (
    OPENAPI_VERSION_3_0,
    OPENAPI_VERSION_3_1,
    OPENAPI_VERSION_3_2,
    DocsRoutes,
    OpenAPIOperationMetadata,
    OpenAPIRegistry,
    OpenAPISpecConfigError,
    SDKIncompatibleError,
    SpecReport,
    SpecWarning,
    WarningCode,
    clear_openapi_registry,
    generate_openapi_report,
    generate_openapi_spec,
    get_openapi_json,
    get_openapi_yaml,
    openapi,
    register_openapi_metadata,
    register_openapi_routes,
    render_swagger_ui,
    scan_endpoint_metadata,
    scan_validation_metadata,
)

Public API surface

Symbol Kind Purpose
openapi decorator Attach operation metadata to function handlers
register_openapi_metadata function Register metadata for dynamically-created endpoints
register_openapi_routes function Explicitly register JSON, YAML, and Swagger UI routes on a supplied app
clear_openapi_registry function Remove all entries from the registry
scan_endpoint_metadata function Auto-discover validation metadata from @validate_http handlers
scan_validation_metadata function Deprecated alias for scan_endpoint_metadata (emits DeprecationWarning; removed in a future minor release)
generate_openapi_spec function Build OpenAPI dictionary from decorator registry
generate_openapi_report function Build the spec plus a deterministic tuple of structured warnings (returns SpecReport)
get_openapi_json function Build OpenAPI and serialize to JSON string
get_openapi_yaml function Build OpenAPI and serialize to YAML string
render_swagger_ui function Return Swagger UI HttpResponse
OpenAPIOperationMetadata dataclass Frozen dataclass for operation metadata
OpenAPIRegistry class Thread-safe registry backing the decorator; pass an instance for isolated (test-friendly) registration
SpecReport dataclass Result of generate_openapi_report: the spec dict plus a warnings tuple
SpecWarning dataclass A single structured warning (code, message, function_name, and optional operation path, method, location) emitted during generation
WarningCode enum Stable string identifiers for warning categories (e.g. version-skew, ambiguous-namespace)
OpenAPISpecConfigError exception Raised for configuration errors
SDKIncompatibleError exception Subclass of OpenAPISpecConfigError; raised when the installed Functions SDK is incompatible
OPENAPI_VERSION_3_0 constant OpenAPI version string "3.0.0"
OPENAPI_VERSION_3_1 constant OpenAPI version string "3.1.0"
OPENAPI_VERSION_3_2 constant OpenAPI version string "3.2.0"

Documentation route registration

routes = register_openapi_routes(
    app,
    title="Orders API",
    version="1.0.0",
    route_prefix="/api",
    auth_level=func.AuthLevel.ANONYMOUS,
)

register_openapi_routes() is an explicit, opt-in convenience over three ordinary app.route(...) registrations. It does not replace Azure Functions routing and performs no import-time registration. The returned frozen DocsRoutes exposes the JSON, YAML, and docs handlers for tests and introspection; all three fields are None when enabled=False.

Customize json_route, yaml_route, docs_route, and name_prefix when the defaults conflict with existing functions. route_prefix controls both the generated spec paths and the URL fetched by Swagger UI. Additional generation arguments such as description, strict, or servers can be supplied through spec_options.

When auth_level is not ANONYMOUS, the docs handler forwards a code query parameter from the docs request to the JSON specification URL so Swagger UI can load it. The key must authorize the JSON route: a host/master key spans functions, while a function-scoped key authorizes only its own function. The key remains in the page URL and can appear in browser history and logs, so use this only in trusted/internal environments; prefer edge-managed session or cookie authentication for broader access.

Decorator behavior model

@openapi stores metadata in a thread-safe registry and the spec functions read from that registry to generate output.

@openapi metadata ---------> internal registry --> generate_openapi_spec --> JSON/YAML endpoint
                                                    @validate_http metadata --> scan_endpoint_metadata(app) --^       `--> render_swagger_ui (docs)

Note

get_openapi_json() and get_openapi_yaml() return strings, not HttpResponse. Wrap the returned value in func.HttpResponse in your Azure Function route.

Warning

If @openapi is the innermost decorator (below @app.route), it runs before the route binding exists. Pass the completed app to the package-root generate_openapi_spec(app=app), get_openapi_json(app=app), get_openapi_yaml(app=app), or generate_openapi_report(app=app). Without binding evidence, generation emits a non-fatal unresolved-route warning before falling back to the function name. The warning remains non-fatal under strict=True, because the fallback can be Azure's correct default route. The low-level functions in azure_functions_openapi.spec intentionally remain SDK-free registry compilers.

Common usage patterns

Minimal endpoint

@openapi(summary="Ping", description="Health check endpoint")
@app.route(route="ping", methods=["GET"])
def ping(req: func.HttpRequest) -> func.HttpResponse:
    return func.HttpResponse("ok", status_code=200)

With Pydantic request and response

class CreateItemRequest(BaseModel):
    name: str


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


@openapi(
    summary="Create item",
    method="post",
    route="/api/items",
    requests=CreateItemRequest,
    responses={
        201: {
            "description": "Created",
            "content": {"application/json": {"schema": ItemResponse}},
        },
    },
)
@app.route(route="items", methods=["POST"])
def create_item(req: func.HttpRequest) -> func.HttpResponse: ...

Note

Here the 201 entry carries the model schema in content.schema while also setting the status description, so a single unified responses= map puts a model schema on a non-200 success status. The request side uses the requests= parameter.

With raw schema dictionaries

@openapi(
    summary="Raw schema example",
    method="post",
    requests={
        "type": "object",
        "properties": {"value": {"type": "string"}},
        "required": ["value"],
    },
    responses={
        200: {
            "description": "OK",
            "content": {
                "application/json": {
                    "schema": {
                        "type": "object",
                        "properties": {"accepted": {"type": "boolean"}},
                    }
                }
            },
        }
    },
)
@app.route(route="raw", methods=["POST"])
def raw(req: func.HttpRequest) -> func.HttpResponse: ...

Querystring parameter (OpenAPI 3.2)

OpenAPI 3.2 adds a querystring parameter location that describes the entire query string with a single schema. Pass a Pydantic model or raw JSON Schema via querystring=; it is emitted only when generating a 3.2.0 document.

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


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

Note

querystring requires openapi_version="3.2.0" (raises OpenAPISpecConfigError under 3.0/3.1). At most one querystring parameter is allowed per operation, and it cannot coexist with any in: query parameter. See Configuration for details.

Expose OpenAPI + Swagger routes

@app.route(route="openapi.json", methods=["GET"])
def openapi_json(req: func.HttpRequest) -> func.HttpResponse:
    return func.HttpResponse(
        get_openapi_json(title="My API", version="1.0.0", app=app), mimetype="application/json"
    )


@app.route(route="openapi.yaml", methods=["GET"])
def openapi_yaml(req: func.HttpRequest) -> func.HttpResponse:
    return func.HttpResponse(
        get_openapi_yaml(title="My API", version="1.0.0", app=app), mimetype="application/x-yaml"
    )


@app.route(route="docs", methods=["GET"])
def docs(req: func.HttpRequest) -> func.HttpResponse:
    return render_swagger_ui(title="My API Docs", openapi_url="/api/openapi.json")

mkdocstrings reference

The sections below are generated directly from source docstrings.

openapi

Decorator that attaches OpenAPI metadata to an Azure Functions handler.

Examples

1 · Minimal “Hello World”

@openapi(summary="Hello", description="Returns plain text.", method="get")
@app.route(route="hello")
def hello(req: func.HttpRequest) -> func.HttpResponse:
    return func.HttpResponse("Hello, world!", status_code=200)

2 · Pydantic-powered JSON API

from pydantic import BaseModel

class TodoRequest(BaseModel):
    title: str
    done: bool = False

class TodoResponse(BaseModel):
    id: int
    title: str
    done: bool

@openapi(
    summary="Update a todo item",
    description="Update a todo and return the updated document.",
    tags=["Todo"],
    parameters=[{"name": "id", "in": "path", "required": True, "schema": {"type": "integer"}}],
    requests=TodoRequest,
    responses=TodoResponse,
    operation_id="updateTodo",
)
@app.route(route="todos/{id}", methods=["PUT"])
def update_todo(req: func.HttpRequest) -> func.HttpResponse:
    # ... business logic ...
    body = TodoRequest.model_validate_json(req.get_body())
    todo = TodoResponse(id=1, **body.model_dump())
    return func.HttpResponse(
        todo.model_dump_json(),
        status_code=200,
        mimetype="application/json",
    )

After starting the Function App you get:

  • Swagger UI → http://localhost:7071/api/docs
  • Raw JSON spec → http://localhost:7071/api/openapi.json

Parameters

summary: Short description shown in Swagger UI. Defaults to None (unset). When infer_docstring=True and this is left unset, it is inferred from the handler docstring's first line; pass "" to explicitly suppress that inference. description: Longer Markdown-enabled description. Defaults to None (unset). When infer_docstring=True and this is left unset, it is inferred from the handler docstring body; pass "" to explicitly suppress that inference. tags: List of group tags. operation_id: Custom operationId (defaults to function name). route: Override for the HTTP route path (e.g. "/items/{id}"). method: Explicit HTTP method for this operation. When omitted, the method is inferred from the @app.route binding: a single methods= value is used directly, and a binding that omits methods= expands to every HTTP method (matching the Azure runtime). A bare @openapi with no route binding and no method= emits a single get operation. parameters: List of raw OpenAPI param objects (query/path/header/cookie). path: Pydantic model whose fields document in: path parameters. Every field becomes required: true. Nested-object fields are rejected. Documentation only — no runtime validation. headers: Pydantic model whose fields document in: header parameters. Requiredness follows the model's optional/required fields. Nested-object fields are rejected. Documentation only — no runtime validation. security: List of OpenAPI Security Requirement Objects. Example: [{"BearerAuth": []}] security_scheme: Security scheme definitions to include in components.securitySchemes. Example: {"BearerAuth": {"type": "http", "scheme": "bearer"}} requests: Request parameter that accepts either a Pydantic model class (used to derive the requestBody schema) or a raw requestBody schema dict. request_body_required: Whether the request body is required. Defaults to True. responses: Response parameter. Accepts either:

* a Pydantic model class (its schema is injected into the first 2xx
  response), or
* a dict keyed by status code whose values are OpenAPI Response Objects.
  Each value may additionally be a bare Pydantic model class as shorthand
  for a JSON body of that schema, and a model class may also appear in the
  `content.<media>.schema` position of a Response Object. This lets a
  single operation express a typed success body together with several
  documented status codes — e.g.
  ``responses={202: AcceptedModel, 422: {"description": "Validation error"}}``.

querystring: OpenAPI 3.2 querystring parameter schema. Accepts either a Pydantic model class or a raw JSON Schema dict, emitted as an in: querystring parameter. Only valid for openapi_version="3.2.0"; raises under 3.0/3.1. querystring_media_type: Media type used to encode the querystring content. Defaults to application/x-www-form-urlencoded. infer_docstring: When True (opt-in, #551), gap-fill summary/description from the handler's docstring for any of those fields left unset (None). Defaults to False so a handler's prose docstring is never published as public API documentation without explicit consent. Return-type response inference is controlled separately by infer_return_types (on by default). infer_return_types: When True (default), gap-fill the 200 response schema from the handler's return annotation whenever no explicit responses= is supplied. Set False to suppress return-type inference entirely (analogous to FastAPI's response_model=None); an explicit responses= always wins regardless of this flag.

Returns

Callable The original function, with its name stored in _openapi_registry.

Source code in src/azure_functions_openapi/decorator.py
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
def openapi(
    # ── basic metadata ───────────────────────────────────────────
    summary: str | None = None,
    description: str | None = None,
    tags: list[str] | None = None,
    operation_id: str | None = None,
    # ── routing information ─────────────────────────────────────
    route: str | None = None,
    method: str | None = None,
    parameters: list[dict[str, Any]] | None = None,
    # ── typed parameters (documentation sugar) ──────────────────
    path: type[BaseModel] | None = None,
    headers: type[BaseModel] | None = None,
    security: list[dict[str, list[str]]] | None = None,
    security_scheme: dict[str, dict[str, Any]] | None = None,
    # ── request / response schema ───────────────────────────────
    requests: type[BaseModel] | dict[str, Any] | None = None,
    request_body_required: bool = True,
    responses: type[BaseModel] | Mapping[int | Literal["default"], Any] | None = None,
    # ── querystring (OpenAPI 3.2 only) ───────────────────────
    querystring: type[BaseModel] | dict[str, Any] | None = None,
    querystring_media_type: str = "application/x-www-form-urlencoded",
    # ── inference toggles ─────────────────────────────────────────
    infer_docstring: bool = False,
    infer_return_types: bool = True,
    # ── retired parameters (removed in 0.24.0, #509) ──────────────
    # Kept only to raise an actionable error on misuse; sentinel-defaulted so
    # unknown keywords still fail static type-checking (#557).
    request_model: Any = _RETIRED_UNSET,
    request_body: Any = _RETIRED_UNSET,
    response_model: Any = _RETIRED_UNSET,
    response: Any = _RETIRED_UNSET,
) -> Callable[[F], F]:
    """
    Decorator that attaches OpenAPI metadata to an Azure Functions handler.

    Examples
    --------
    ### 1 · Minimal “Hello World”

    ```python
    @openapi(summary="Hello", description="Returns plain text.", method="get")
    @app.route(route="hello")
    def hello(req: func.HttpRequest) -> func.HttpResponse:
        return func.HttpResponse("Hello, world!", status_code=200)
    ```

    ### 2 · Pydantic-powered JSON API

    ```python
    from pydantic import BaseModel

    class TodoRequest(BaseModel):
        title: str
        done: bool = False

    class TodoResponse(BaseModel):
        id: int
        title: str
        done: bool

    @openapi(
        summary="Update a todo item",
        description="Update a todo and return the updated document.",
        tags=["Todo"],
        parameters=[{"name": "id", "in": "path", "required": True, "schema": {"type": "integer"}}],
        requests=TodoRequest,
        responses=TodoResponse,
        operation_id="updateTodo",
    )
    @app.route(route="todos/{id}", methods=["PUT"])
    def update_todo(req: func.HttpRequest) -> func.HttpResponse:
        # ... business logic ...
        body = TodoRequest.model_validate_json(req.get_body())
        todo = TodoResponse(id=1, **body.model_dump())
        return func.HttpResponse(
            todo.model_dump_json(),
            status_code=200,
            mimetype="application/json",
        )
    ```

    After starting the Function App you get:

    * **Swagger UI** → `http://localhost:7071/api/docs`
    * **Raw JSON spec** → `http://localhost:7071/api/openapi.json`

    Parameters
    ----------
    summary:
        Short description shown in Swagger UI. Defaults to ``None`` (unset).
        When ``infer_docstring=True`` and this is left unset, it is inferred
        from the handler docstring's first line; pass ``""`` to explicitly
        suppress that inference.
    description:
        Longer Markdown-enabled description. Defaults to ``None`` (unset).
        When ``infer_docstring=True`` and this is left unset, it is inferred
        from the handler docstring body; pass ``""`` to explicitly suppress
        that inference.
    tags:
        List of group tags.
    operation_id:
        Custom operationId (defaults to function name).
    route:
        Override for the HTTP route path (e.g. "/items/{id}").
    method:
        Explicit HTTP method for this operation. When omitted, the method is
        inferred from the ``@app.route`` binding: a single ``methods=`` value is
        used directly, and a binding that omits ``methods=`` expands to every
        HTTP method (matching the Azure runtime). A bare ``@openapi`` with no
        route binding and no ``method=`` emits a single ``get`` operation.
    parameters:
        List of raw OpenAPI param objects (query/path/header/cookie).
    path:
        Pydantic model whose fields document ``in: path`` parameters. Every
        field becomes ``required: true``. Nested-object fields are rejected.
        Documentation only — no runtime validation.
    headers:
        Pydantic model whose fields document ``in: header`` parameters.
        Requiredness follows the model's optional/required fields. Nested-object
        fields are rejected. Documentation only — no runtime validation.
    security:
        List of OpenAPI Security Requirement Objects.
        Example: [{"BearerAuth": []}]
    security_scheme:
        Security scheme definitions to include in components.securitySchemes.
        Example: {"BearerAuth": {"type": "http", "scheme": "bearer"}}
    requests:
        Request parameter that accepts either a Pydantic model class (used to
        derive the requestBody schema) or a raw requestBody schema dict.
    request_body_required:
        Whether the request body is required. Defaults to True.
    responses:
        Response parameter. Accepts either:

        * a Pydantic model class (its schema is injected into the first 2xx
          response), or
        * a dict keyed by status code whose values are OpenAPI Response Objects.
          Each value may additionally be a bare Pydantic model class as shorthand
          for a JSON body of that schema, and a model class may also appear in the
          `content.<media>.schema` position of a Response Object. This lets a
          single operation express a typed success body together with several
          documented status codes — e.g.
          ``responses={202: AcceptedModel, 422: {"description": "Validation error"}}``.
    querystring:
        OpenAPI 3.2 querystring parameter schema. Accepts either a Pydantic
        model class or a raw JSON Schema dict, emitted as an ``in: querystring``
        parameter. Only valid for ``openapi_version="3.2.0"``; raises under
        3.0/3.1.
    querystring_media_type:
        Media type used to encode the querystring content. Defaults to
        ``application/x-www-form-urlencoded``.
    infer_docstring:
        When ``True`` (opt-in, #551), gap-fill ``summary``/``description``
        from the handler's docstring for any of those fields left unset
        (``None``). Defaults to ``False`` so a handler's prose docstring is
        never published as public API documentation without explicit consent.
        Return-type response inference is controlled separately by
        ``infer_return_types`` (on by default).
    infer_return_types:
        When ``True`` (default), gap-fill the ``200`` response schema from the
        handler's return annotation whenever no explicit ``responses=`` is
        supplied. Set ``False`` to suppress return-type inference entirely
        (analogous to FastAPI's ``response_model=None``);
        an explicit
        ``responses=`` always wins regardless of this flag.

    Returns
    -------
    Callable
        The original function, with its name stored in `_openapi_registry`.
    """
    # Reject any retired parameter eagerly with actionable guidance (#557)
    # before any handler is decorated.
    _reject_retired_kwargs(
        request_model=request_model,
        request_body=request_body,
        response_model=response_model,
        response=response,
    )

    def decorator(func: F) -> F:
        target_name = getattr(func, "__qualname__", getattr(func, "__name__", "<unknown>"))
        try:
            original_func, metadata_func = _resolve_metadata_target(func)
            target_name = f"{metadata_func.__module__}.{metadata_func.__qualname__}"

            # Auto-detect route/method from FunctionBuilder bindings when
            # not explicitly provided by the caller.
            effective_route = route
            effective_method = method
            binding_route, binding_method, binding_multi, binding_methods_unspecified = (
                _extract_binding_hints(func)
            )
            if effective_route is None and binding_route is not None:
                effective_route = binding_route
            if effective_method is None:
                if binding_method is not None:
                    effective_method = binding_method
                elif binding_multi:
                    raise OpenAPISpecConfigError(
                        f"Cannot infer a single HTTP method for '{metadata_func.__name__}': "
                        "@app.route declares multiple methods. "
                        "Pass method=... explicitly to @openapi, "
                        "or create a separate @openapi-decorated function per method."
                    )

            # All-method expansion (see spec generator) is only justified when a
            # real httptrigger binding is present but omits ``methods=``; a bare
            # @openapi with no binding leaves the method unresolved and must emit
            # a single operation instead of fanning out to every HTTP verb (#347).
            expand_all_methods = effective_method is None and binding_methods_unspecified

            # Enhanced input validation and sanitization
            validated_route = _validate_and_sanitize_route(effective_route, metadata_func.__name__)
            validated_method = _validate_method(effective_method, metadata_func.__name__)
            sanitized_operation_id = _validate_and_sanitize_operation_id(
                operation_id, metadata_func.__name__
            )
            validated_parameters = _validate_parameters(parameters, metadata_func.__name__)
            validated_parameters = _merge_typed_parameters(
                validated_parameters, path, headers, metadata_func.__name__
            )
            validated_security = _validate_security(security, metadata_func.__name__)
            validated_security_scheme = _validate_security_scheme(
                security_scheme, metadata_func.__name__
            )
            validated_tags = _validate_tags(tags, metadata_func.__name__)

            resolved_request_model: type[BaseModel] | None = None
            resolved_request_body: dict[str, Any] | None = None
            resolved_response_model: type[BaseModel] | None = None
            resolved_response: dict[int | str, dict[str, Any]] | None = None

            if requests is not None:
                if isinstance(requests, dict):
                    resolved_request_body = requests
                elif isinstance(requests, type) and issubclass(requests, BaseModel):
                    resolved_request_model = requests
                else:
                    raise ValueError(
                        "'requests' must be either a Pydantic BaseModel subclass or a dictionary."
                    )

            if responses is not None:
                if isinstance(responses, Mapping):
                    resolved_response = _normalize_unified_responses(
                        responses, metadata_func.__name__
                    )
                elif _is_pydantic_model(responses):
                    resolved_response_model = responses
                else:
                    raise ValueError(
                        "'responses' must be either a Pydantic BaseModel subclass or a dictionary."
                    )

            # ── return-type inference (P1-A) ─────────────────────────────
            # Lowest-precedence gap-fill: only when the user supplied no
            # explicit ``responses=``. An inferred response is marked so that
            # scan-time validation/explicit metadata can supersede it (Oracle
            # precedence: explicit > validation > inference).
            response_inferred = False
            if responses is None and infer_return_types:
                inferred_model, inferred_response = _infer_response_from_return(metadata_func)
                if inferred_model is not None:
                    resolved_response_model = inferred_model
                    response_inferred = True
                elif inferred_response is not None:
                    resolved_response = inferred_response
                    response_inferred = True

            # ── docstring inference (P1-A Phase 2, opt-in #551) ──────────
            # Opt-in (#551): docstring inference is off by default so a
            # handler's prose docstring is never published as public API
            # documentation without explicit consent. When enabled, it stays
            # lowest-precedence gap-fill, per field: only when the user gave
            # no explicit ``summary=`` / ``description=``. ``None`` is the
            # "unset" sentinel, so an explicit ``summary=""`` / ``description=""``
            # is an intentional override and suppresses inference for that field.
            # The handler docstring's first line becomes the summary and the
            # remainder the description.
            effective_summary = summary or ""
            effective_description = description or ""
            if infer_docstring and (summary is None or description is None):
                inferred_summary, inferred_description = _infer_doc_metadata(metadata_func)
                if summary is None:
                    effective_summary = inferred_summary
                if description is None:
                    effective_description = inferred_description

            resolved_querystring_model: type[BaseModel] | None = None
            resolved_querystring_schema: dict[str, Any] | None = None
            if querystring is not None:
                if isinstance(querystring, dict):
                    resolved_querystring_schema = querystring
                elif isinstance(querystring, type) and issubclass(querystring, BaseModel):
                    resolved_querystring_model = querystring
                else:
                    raise ValueError(
                        "'querystring' must be either a Pydantic BaseModel subclass "
                        "or a dictionary."
                    )

            # Validate request/response models
            _validate_models(
                resolved_request_model,
                resolved_response_model,
                metadata_func.__name__,
            )

            function_id = ensure_canonical_identity(metadata_func)

            with _registry_lock:
                registry_key = metadata_func.__name__
                existing = registry.get(registry_key)
                if existing and existing.get("_function_id") != function_id:
                    existing_id = existing.get("_function_id")
                    if isinstance(existing_id, str):
                        # Preserve displaced entry under its fully-qualified id
                        registry.setdefault(existing_id, existing)

                registry.set(
                    registry_key,
                    {
                        # ── basic metadata ────────────────────────────────────────
                        "summary": effective_summary,
                        "description": effective_description,
                        "tags": validated_tags,
                        "operation_id": sanitized_operation_id,
                        # ── routing info ─────────────────────────────────────────
                        "route": validated_route,
                        "method": validated_method,
                        "_route_evidence": route is not None or adapters.is_function_builder(func),
                        # Evidence that the runtime answers every HTTP method
                        # (binding present, ``methods=`` omitted). Gates all-method
                        # expansion in the spec generator; a bare @openapi stays
                        # single-operation (#347).
                        "_expand_all_methods": expand_all_methods,
                        "parameters": validated_parameters,
                        "security": validated_security,
                        "_security_declared": security is not None,
                        "security_scheme": validated_security_scheme,
                        # ── request / response schema ────────────────────────
                        "request_model": resolved_request_model,
                        "request_body": resolved_request_body,
                        "request_body_required": request_body_required,
                        "response_model": resolved_response_model,
                        "response": resolved_response or {},
                        # Marks ``response``/``response_model`` as return-type
                        # inferred (P1-A) so scan-time reconciliation lets
                        # validation/explicit metadata supersede it.
                        "_response_inferred": response_inferred,
                        # ── querystring (OpenAPI 3.2) ────────────────────────
                        "querystring_model": resolved_querystring_model,
                        "querystring_schema": resolved_querystring_schema,
                        "querystring_media_type": querystring_media_type,
                        "function_name": metadata_func.__name__,
                        "_function_id": function_id,
                    },
                )

            logger.debug(f"Registered OpenAPI metadata for function '{metadata_func.__name__}'")
            return cast(F, original_func)

        except OpenAPISpecConfigError as e:
            logger.error(f"Failed to register OpenAPI metadata for '{target_name}': {str(e)}")
            raise
        except (ValueError, RuntimeError, TypeError) as e:
            # ValueError/TypeError: validation failures (input contract).
            # SDK-internal access failures raise SDKIncompatibleError, which is a
            # subclass of OpenAPISpecConfigError and is handled by the branch above;
            # any RuntimeError reaching here is unexpected and re-raised unchanged
            # to avoid double-wrapping.
            logger.error(f"Failed to register OpenAPI metadata for '{target_name}': {str(e)}")
            raise
        except Exception as e:
            logger.error(f"Failed to register OpenAPI metadata for '{target_name}': {str(e)}")
            raise RuntimeError(
                f"Failed to register OpenAPI metadata for '{target_name}': {e}"
            ) from e

    return decorator

generate_openapi_spec

Compile a spec, optionally reconciling routes from a FunctionApp first.

Source code in src/azure_functions_openapi/__init__.py
def generate_openapi_spec(
    title: str = "API",
    version: str = "1.0.0",
    openapi_version: str = OPENAPI_VERSION_3_1,
    description: str = DEFAULT_OPENAPI_INFO_DESCRIPTION,
    security_schemes: dict[str, dict[str, Any]] | None = None,
    route_prefix: str = "/api",
    strict: bool = False,
    registry: OpenAPIRegistry | None = None,
    hoist_flat_schemas: bool = False,
    infer_auth_level: bool = False,
    servers: list[dict[str, Any]] | None = None,
    contact: dict[str, Any] | None = None,
    license: dict[str, Any] | None = None,
    external_docs: dict[str, Any] | None = None,
    tags: list[dict[str, Any]] | None = None,
    app: object | None = None,
) -> dict[str, Any]:
    """Compile a spec, optionally reconciling routes from a FunctionApp first."""
    _prepare_generation(app, route_prefix, registry)
    return _generate_openapi_spec(
        title=title,
        version=version,
        openapi_version=openapi_version,
        description=description,
        security_schemes=security_schemes,
        route_prefix=route_prefix,
        strict=strict,
        registry=registry,
        hoist_flat_schemas=hoist_flat_schemas,
        infer_auth_level=infer_auth_level,
        servers=servers,
        contact=contact,
        license=license,
        external_docs=external_docs,
        tags=tags,
    )

get_openapi_json

Return JSON after optionally reconciling routes from a completed FunctionApp.

Source code in src/azure_functions_openapi/__init__.py
def get_openapi_json(
    title: str = "API",
    version: str = "1.0.0",
    openapi_version: str = OPENAPI_VERSION_3_1,
    description: str = DEFAULT_OPENAPI_INFO_DESCRIPTION,
    security_schemes: dict[str, dict[str, Any]] | None = None,
    route_prefix: str = "/api",
    strict: bool = False,
    registry: OpenAPIRegistry | None = None,
    hoist_flat_schemas: bool = False,
    infer_auth_level: bool = False,
    servers: list[dict[str, Any]] | None = None,
    contact: dict[str, Any] | None = None,
    license: dict[str, Any] | None = None,
    external_docs: dict[str, Any] | None = None,
    tags: list[dict[str, Any]] | None = None,
    app: object | None = None,
) -> str:
    """Return JSON after optionally reconciling routes from a completed FunctionApp."""
    try:
        spec = generate_openapi_spec(
            title,
            version,
            openapi_version,
            description,
            security_schemes,
            route_prefix,
            strict,
            registry,
            hoist_flat_schemas,
            infer_auth_level,
            servers,
            contact,
            license,
            external_docs,
            tags,
            app,
        )
        return json.dumps(spec, indent=2, ensure_ascii=False)
    except OpenAPISpecConfigError:
        raise
    except Exception as error:
        raise RuntimeError("Failed to generate OpenAPI JSON") from error

get_openapi_yaml

Return YAML after optionally reconciling routes from a completed FunctionApp.

Source code in src/azure_functions_openapi/__init__.py
def get_openapi_yaml(
    title: str = "API",
    version: str = "1.0.0",
    openapi_version: str = OPENAPI_VERSION_3_1,
    description: str = DEFAULT_OPENAPI_INFO_DESCRIPTION,
    security_schemes: dict[str, dict[str, Any]] | None = None,
    route_prefix: str = "/api",
    strict: bool = False,
    registry: OpenAPIRegistry | None = None,
    hoist_flat_schemas: bool = False,
    infer_auth_level: bool = False,
    servers: list[dict[str, Any]] | None = None,
    contact: dict[str, Any] | None = None,
    license: dict[str, Any] | None = None,
    external_docs: dict[str, Any] | None = None,
    tags: list[dict[str, Any]] | None = None,
    app: object | None = None,
) -> str:
    """Return YAML after optionally reconciling routes from a completed FunctionApp."""
    try:
        spec = generate_openapi_spec(
            title,
            version,
            openapi_version,
            description,
            security_schemes,
            route_prefix,
            strict,
            registry,
            hoist_flat_schemas,
            infer_auth_level,
            servers,
            contact,
            license,
            external_docs,
            tags,
            app,
        )
        return yaml.safe_dump(spec, sort_keys=False, allow_unicode=True)
    except OpenAPISpecConfigError:
        raise
    except Exception as error:
        raise RuntimeError("Failed to generate OpenAPI YAML") from error

render_swagger_ui

Render Swagger UI with enhanced security headers and CSP protection.

Parameters:

Name Type Description Default
title str

Page title for the Swagger UI

'API Documentation'
openapi_url str

URL to the OpenAPI specification

'/api/openapi.json'
custom_csp str | None

Custom Content Security Policy (optional)

None
enable_client_logging bool

Whether to enable browser-side response logging

False

Returns:

Type Description
HttpResponse

HttpResponse with Swagger UI HTML and security headers

Source code in src/azure_functions_openapi/swagger_ui.py
def render_swagger_ui(
    title: str = "API Documentation",
    openapi_url: str = "/api/openapi.json",
    custom_csp: str | None = None,
    enable_client_logging: bool = False,
) -> HttpResponse:
    """
    Render Swagger UI with enhanced security headers and CSP protection.

    Parameters:
        title: Page title for the Swagger UI
        openapi_url: URL to the OpenAPI specification
        custom_csp: Custom Content Security Policy (optional)
        enable_client_logging: Whether to enable browser-side response logging

    Returns:
        HttpResponse with Swagger UI HTML and security headers
    """
    nonce = secrets.token_urlsafe(16)

    # Enhanced CSP policy for better security
    default_csp = (
        "default-src 'self'; "
        f"script-src 'self' 'nonce-{nonce}' https://cdn.jsdelivr.net; "
        "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
        "img-src 'self' data: https:; "
        "font-src 'self' https://cdn.jsdelivr.net; "
        "connect-src 'self'; "
        "frame-ancestors 'none'; "
        "base-uri 'self'; "
        "form-action 'self'"
    )

    csp_policy = custom_csp.replace("{nonce}", nonce) if custom_csp else default_csp

    # Validate and sanitize inputs
    sanitized_title = _sanitize_html_content(title)
    sanitized_url = _sanitize_url(openapi_url)

    # Escape for safe embedding in HTML attributes and JS string literals
    safe_title = html.escape(sanitized_title, quote=True)
    safe_csp = html.escape(csp_policy, quote=True)
    safe_url_js = json.dumps(sanitized_url)  # produces "..." with proper escaping

    response_interceptor = """
            responseInterceptor: function(response) {
              return response;
            }
    """
    if enable_client_logging:
        response_interceptor = """
            responseInterceptor: function(response) {
              console.log('API Response:', response.status, response.url);
              return response;
            }
    """

    html_content = f"""
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta http-equiv="Content-Security-Policy" content="{safe_csp}">
        <meta http-equiv="X-Content-Type-Options" content="nosniff">
        <meta http-equiv="X-Frame-Options" content="DENY">
        <meta http-equiv="Referrer-Policy" content="strict-origin-when-cross-origin">
        <title>{safe_title}</title>
        <link rel="stylesheet"
              type="text/css"
              integrity="{_SWAGGER_UI_CSS_SRI}"
              crossorigin="anonymous"
              href="{_SWAGGER_UI_CDN_BASE}/swagger-ui.css" />
      </head>
      <body>
        <div id="swagger-ui"></div>
        <script src="{_SWAGGER_UI_CDN_BASE}/swagger-ui-bundle.js"
                integrity="{_SWAGGER_UI_BUNDLE_SRI}"
                crossorigin="anonymous"></script>
        <script nonce="{nonce}">
          // Enhanced security configuration
          const ui = SwaggerUIBundle({{
            url: {safe_url_js},
            dom_id: '#swagger-ui',
            presets: [SwaggerUIBundle.presets.apis],
            layout: 'BaseLayout',
            validatorUrl: null,  // Disable external validator for security
            tryItOutEnabled: true,
            supportedSubmitMethods: ['get', 'post', 'put', 'delete', 'patch', 'head', 'options'],
            requestInterceptor: function(request) {{
              // Add security headers to requests
              request.headers['X-Requested-With'] = 'XMLHttpRequest';
              return request;
            }},
            {response_interceptor}
          }});
        </script>
      </body>
    </html>
    """

    # Create response with security headers
    response = HttpResponse(html_content, mimetype="text/html")

    # Add additional security headers
    headers = {
        "Content-Security-Policy": csp_policy,
        "X-Content-Type-Options": "nosniff",
        "X-Frame-Options": "DENY",
        "Referrer-Policy": "strict-origin-when-cross-origin",
        "Strict-Transport-Security": "max-age=31536000; includeSubDomains",
        "Cache-Control": "no-cache, no-store, must-revalidate",
        "Pragma": "no-cache",
        "Expires": "0",
    }

    for header, value in headers.items():
        response.headers[header] = value

    logger.info(f"Swagger UI rendered with enhanced security headers for URL: {sanitized_url}")
    return response

Bridge: Auto-discover validation metadata

scan_endpoint_metadata

Scans a FunctionApp for HTTP-triggered functions decorated with @validate_http and auto-registers their Pydantic models in the OpenAPI registry.

from azure_functions_openapi import scan_endpoint_metadata

# Call after all routes are registered
scan_endpoint_metadata(app)

No extra dependencies required

scan_endpoint_metadata() reads the convention-based metadata attribute written by @validate_http. No import from azure-functions-validation is needed — just install both packages in your project.

Merge rules

Scenario Behavior
Only @validate_http Auto-registers discovered models
Only @openapi Existing behavior unchanged
Both with same models Merges additional OpenAPI fields
Both with different models Raises OpenAPISpecConfigError
Explicit @openapi Always takes precedence

Response compatibility is determined from resolved JSON Schema, so a Pydantic model in @openapi is equivalent to the same schema emitted by @validate_http. For an equivalent status, the merged operation contains one response entry and keeps the explicit summary and description (a blank discovered description never replaces explicit text). Different schemas for a shared status, request body, or parameter raise OpenAPISpecConfigError with the method, route or function name, conflicting item, and the @openapi and @validate_http source names.

scan_validation_metadata is deprecated

scan_validation_metadata() is a deprecated alias for scan_endpoint_metadata(). The scanner now consumes the namespace-neutral "endpoint" contract (the "validation" namespace is only a fallback), so the old name is a misnomer. Calling it forwards unchanged but emits a DeprecationWarning, and it will be removed in a future minor release. Switch to scan_endpoint_metadata().

Structured warnings

generate_openapi_report() mirrors generate_openapi_spec() but returns a SpecReport — the identical spec mapping plus a deterministic warnings tuple. This lets CI gate a build on API drift without parsing log output.

It accepts the same document options as generate_openapi_spec(), including infer_auth_level, servers, contact, license, external_docs, and top-level tags:

report = generate_openapi_report(
    title="My API",
    servers=[{"url": "https://api.example.com"}],
    tags=[{"name": "users"}],
)
from azure_functions_openapi import generate_openapi_report

report = generate_openapi_report(title="My API", version="1.0.0")
if report.warnings:
    for w in report.warnings:
        print(w.code, w.message, w.function_name, w.method, w.path, w.location)
    raise SystemExit(1)  # fail the build on any warning
spec = report.spec
Symbol Purpose
SpecReport Dataclass with spec: dict and warnings: tuple[SpecWarning, ...]
SpecWarning Frozen dataclass: code: WarningCode, message: str, function_name: str \| None, plus optional path, method, and location; to_dict() includes every field for JSON
WarningCode str-based enum of stable codes: version-skew, ambiguous-namespace, duplicate-operation, spec-validation, discovery-skipped, empty-discovery, method-binding-mismatch

When conversion of an explicit request or response model fails, strict generation raises an error naming the HTTP method, normalized emitted path, function or registry identity, and failure location (request body or response <status>). Non-strict generation preserves the fallback behavior and emits a schema-substitution warning with the same context in its structured fields.

While not part of the top-level runtime import list for app code, these internals are useful when debugging:

  • Registry accessor: azure_functions_openapi.decorator.get_openapi_registry
  • Route sanitizer: azure_functions_openapi.utils.validate_route_path
  • Operation ID sanitizer: azure_functions_openapi.utils.sanitize_operation_id

Version constants

Use these constants for explicit version selection:

from azure_functions_openapi import OPENAPI_VERSION_3_0, OPENAPI_VERSION_3_1

spec_30 = get_openapi_json(openapi_version=OPENAPI_VERSION_3_0)
spec_31 = get_openapi_json(openapi_version=OPENAPI_VERSION_3_1)

Tip

Prefer constants over hardcoded strings to avoid typos and keep version intent explicit in code review.