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,
    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,
    render_swagger_ui,
    scan_endpoint_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
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) 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"
## 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.

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"), 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"), 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
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
783
784
785
786
787
788
789
790
791
792
793
794
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,
                        # 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_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 an OpenAPI specification from the registry.

Parameters:

Name Type Description Default
title str

API title

'API'
version str

API version

'1.0.0'
openapi_version str

OpenAPI specification version ("3.0.0", "3.1.0", or "3.2.0")

OPENAPI_VERSION_3_1
description str

Description for the OpenAPI info object

DEFAULT_OPENAPI_INFO_DESCRIPTION
security_schemes dict[str, dict[str, Any]] | None

Security scheme definitions for components.securitySchemes. Example: {"BearerAuth": {"type": "http", "scheme": "bearer"}}

None
route_prefix str

HTTP route prefix from host.json (extensions.http.routePrefix). Defaults to "/api". Pass "" for hosts that disable the prefix or a custom value such as "/v1". Routes that already start with the prefix are not re-prefixed.

DEFAULT_ROUTE_PREFIX
strict bool

When True, raise on any registry entry processing failure instead of logging and skipping. Useful for CI/build-time validation where a missing path should fail the build.

False
hoist_flat_schemas bool

When True (opt-in, #375), structured flat schemas (objects/arrays with no inline $defs) are promoted into components.schemas under their title and replaced with a $ref, deduplicating schemas reused across endpoints. Defaults to False to preserve the verbatim inline-schema behaviour.

False
infer_auth_level bool

When True (opt-in, #482), derive an OpenAPI security requirement from each operation's Azure Functions auth_level (captured on the binding during the metadata scan). FUNCTION/ADMIN map to an apiKey x-functions-key scheme named AzureFunctionKey; ANONYMOUS injects nothing. Inference is only applied to operations that supply no explicit @openapi(security=...) — user-declared security always wins. Requires the FunctionApp-scan path (e.g. CLI module:variable); a plain @openapi-only registry carries no auth_level. Defaults to False for full backward compatibility.

False
servers list[dict[str, Any]] | None

Optional list of OpenAPI Server Objects emitted at the document's top-level servers field (#494). When None, no servers key is added.

None
contact dict[str, Any] | None

Optional Contact Object merged into info.contact (#494).

None
license dict[str, Any] | None

Optional License Object merged into info.license (#494).

None
external_docs dict[str, Any] | None

Optional External Documentation Object emitted at the document's top-level externalDocs field (#494).

None
tags list[dict[str, Any]] | None

Optional list of top-level Tag Objects emitted at the document's tags field (#494). Distinct from per-operation tags.

None

Returns:

Type Description
dict[str, Any]

OpenAPI specification dictionary

Source code in src/azure_functions_openapi/spec.py
 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
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
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 = DEFAULT_ROUTE_PREFIX,
    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,
) -> dict[str, Any]:
    """
    Compile an OpenAPI specification from the registry.

    Parameters:
        title: API title
        version: API version
        openapi_version: OpenAPI specification version ("3.0.0", "3.1.0", or "3.2.0")
        description: Description for the OpenAPI info object
        security_schemes: Security scheme definitions for components.securitySchemes.
            Example: {"BearerAuth": {"type": "http", "scheme": "bearer"}}
        route_prefix: HTTP route prefix from ``host.json``
            (``extensions.http.routePrefix``). Defaults to ``"/api"``. Pass
            ``""`` for hosts that disable the prefix or a custom value such
            as ``"/v1"``. Routes that already start with the prefix are not
            re-prefixed.
        strict: When ``True``, raise on any registry entry processing failure
            instead of logging and skipping. Useful for CI/build-time
            validation where a missing path should fail the build.
        hoist_flat_schemas: When ``True`` (opt-in, #375), structured flat
            schemas (objects/arrays with no inline ``$defs``) are promoted into
            ``components.schemas`` under their ``title`` and replaced with a
            ``$ref``, deduplicating schemas reused across endpoints. Defaults to
            ``False`` to preserve the verbatim inline-schema behaviour.
        infer_auth_level: When ``True`` (opt-in, #482), derive an OpenAPI
            security requirement from each operation's Azure Functions
            ``auth_level`` (captured on the binding during the metadata scan).
            ``FUNCTION``/``ADMIN`` map to an ``apiKey`` ``x-functions-key``
            scheme named ``AzureFunctionKey``; ``ANONYMOUS`` injects nothing.
            Inference is only applied to operations that supply no explicit
            ``@openapi(security=...)`` — user-declared security always wins.
            Requires the FunctionApp-scan path (e.g. CLI ``module:variable``);
            a plain ``@openapi``-only registry carries no ``auth_level``.
            Defaults to ``False`` for full backward compatibility.
        servers: Optional list of OpenAPI Server Objects emitted at the
            document's top-level ``servers`` field (#494). When ``None``, no
            ``servers`` key is added.
        contact: Optional Contact Object merged into ``info.contact`` (#494).
        license: Optional License Object merged into ``info.license`` (#494).
        external_docs: Optional External Documentation Object emitted at the
            document's top-level ``externalDocs`` field (#494).
        tags: Optional list of top-level Tag Objects emitted at the document's
            ``tags`` field (#494). Distinct from per-operation ``tags``.

    Returns:
        OpenAPI specification dictionary
    """
    if openapi_version not in (OPENAPI_VERSION_3_0, OPENAPI_VERSION_3_1, OPENAPI_VERSION_3_2):
        raise OpenAPISpecConfigError(
            f"Unsupported OpenAPI version: {openapi_version}. Supported: "
            f"{OPENAPI_VERSION_3_0}, {OPENAPI_VERSION_3_1}, {OPENAPI_VERSION_3_2}"
        )

    normalized_prefix = normalize_route_prefix(route_prefix)

    try:
        if registry is not None:
            registry_entries = registry.snapshot()
        else:
            registry_entries = get_openapi_registry()
        # Duplicate operations are fully recomputed by the loop below, so clear
        # the channel first: a collision resolved since a prior generation must
        # not linger on the (process-wide or injected) registry and resurface
        # here (#393).
        _diag_registry = registry if registry is not None else _default_registry
        _diag_registry.clear_duplicate_operations()
        _diag_registry.clear_downgrade_drops()
        paths: dict[str, dict[str, Any]] = {}
        components: dict[str, Any] = {"schemas": {}}

        for func_name, meta in registry_entries.items():
            try:
                logical_name = meta.get("function_name") or func_name
                # route & method --------------------------------------------------
                raw_path = f"/{(meta.get('route') or logical_name).lstrip('/')}"
                path = apply_route_prefix(raw_path, normalized_prefix)
                # An unspecified method (``None``) expands to the full HTTP set
                # ONLY when there is binding evidence that the Azure runtime
                # answers every method (an ``@app.route`` binding that omits
                # ``methods=``), recorded as ``_expand_all_methods`` at
                # registration. A bare ``@openapi`` with no binding leaves the
                # method unresolved and emits a single ``get`` operation, and an
                # explicit method is emitted as a single operation, unchanged.
                raw_method = meta.get("method")
                if raw_method is None:
                    if meta.get("_expand_all_methods"):
                        methods_to_emit = list(ALL_HTTP_METHODS)
                        methods_expanded = True
                    else:
                        methods_to_emit = ["get"]
                        methods_expanded = False
                else:
                    methods_to_emit = [str(raw_method).lower()]
                    methods_expanded = False

                # responses -------------------------------------------------------
                responses: dict[str, Any] = {}
                for status, detail in meta.get("response", {}).items():
                    resp = dict(detail)
                    resp.setdefault("description", "")
                    resp_content = resp.get("content")
                    if isinstance(resp_content, dict):
                        hoisted_content: dict[str, Any] = {}
                        for media, media_obj in resp_content.items():
                            if isinstance(media_obj, dict) and any(
                                key in media_obj for key in _MEDIA_SCHEMA_KEYS
                            ):
                                new_media_obj = dict(media_obj)
                                for schema_key in _MEDIA_SCHEMA_KEYS:
                                    if schema_key in new_media_obj:
                                        new_media_obj[schema_key] = _resolve_media_schema(
                                            new_media_obj[schema_key],
                                            components,
                                            hoist_flat_schemas,
                                        )
                                if (
                                    "itemSchema" in new_media_obj
                                    and openapi_version != OPENAPI_VERSION_3_2
                                ):
                                    # itemSchema is an OpenAPI 3.2-only media
                                    # key; on a pre-3.2 target its streaming
                                    # semantics are lost. Route this through the
                                    # same structured downgrade-drop channel used
                                    # for operation-level drops (#479/#492) so
                                    # ``collect_spec_warnings`` /
                                    # ``--fail-on-warnings`` can observe the lost
                                    # 3.2 contract, and preserve the user-facing
                                    # RuntimeWarning using the *same* message
                                    # string (single source, no divergent text).
                                    downgrade_message = (
                                        f"Response media type '{media}' for "
                                        f"function '{func_name}' uses "
                                        f"'itemSchema', which is an OpenAPI 3.2 "
                                        f"feature for sequential/streaming media "
                                        f"types, but the target openapi_version "
                                        f"is {openapi_version}. The field is "
                                        f"emitted as-is but may not be understood "
                                        f"by 3.0/3.1 tooling. Use "
                                        f"openapi_version='3.2.0' for streaming "
                                        f"responses."
                                    )
                                    _diag_registry.add_downgrade_drop(
                                        downgrade_message
                                    )
                                    warnings.warn(
                                        downgrade_message,
                                        RuntimeWarning,
                                        stacklevel=2,
                                    )
                                media_obj = new_media_obj
                            hoisted_content[media] = media_obj
                        resp["content"] = hoisted_content
                    responses[str(status)] = resp

                if meta.get("response_model"):
                    try:
                        model_schema = model_to_schema(meta["response_model"], components)
                        target_status = "200"
                        for status_key in responses:
                            key = str(status_key)
                            if key.isdigit() and 200 <= int(key) < 300:
                                target_status = key
                                break

                        if target_status not in responses:
                            responses[target_status] = {
                                "description": "Successful Response",
                                "content": {"application/json": {"schema": model_schema}},
                            }
                        else:
                            content = responses[target_status].setdefault("content", {})
                            if not isinstance(content, dict):
                                content = {}
                                responses[target_status]["content"] = content

                            json_content = content.setdefault("application/json", {})
                            if not isinstance(json_content, dict):
                                json_content = {}
                                content["application/json"] = json_content

                            json_content.setdefault("schema", model_schema)
                    except Exception as e:
                        logger.warning(
                            f"Failed to generate response schema for {func_name}: {str(e)}"
                        )
                        _ensure_default_response(responses)

                _ensure_default_response(responses)

                # Method-independent operation pieces, computed once and then
                # deep-copied per emitted method so the OpenAPI 3.1 conversion
                # (which mutates operation schemas in place) never aliases across
                # path-item entries.
                # parameters ------------------------------------------------------
                parameters: list[dict[str, Any]] = meta.get("parameters", [])
                op_parameters: list[dict[str, Any]] | None = None
                if parameters:
                    op_parameters = [
                        {
                            **param,
                            "schema": hoist_inline_defs(
                                param["schema"],
                                components,
                                hoist_flat=hoist_flat_schemas,
                            ),
                        }
                        if isinstance(param, dict) and "schema" in param
                        else param
                        for param in parameters
                    ]

                # querystring (OpenAPI 3.2 only) ---------------------------------
                qs_model = meta.get("querystring_model")
                qs_schema = meta.get("querystring_schema")
                has_querystring = qs_model is not None or qs_schema is not None

                # Count querystring entries supplied through the raw
                # ``parameters`` escape hatch so gating/validation covers both
                # the dedicated ``querystring=`` surface and manual parameters.
                raw_querystring_count = sum(
                    1
                    for p in (op_parameters or [])
                    if isinstance(p, dict) and p.get("in") == "querystring"
                )
                total_querystring = raw_querystring_count + (1 if has_querystring else 0)

                if total_querystring and openapi_version != OPENAPI_VERSION_3_2:
                    raise OpenAPISpecConfigError(
                        f"querystring parameters require openapi_version="
                        f"'{OPENAPI_VERSION_3_2}', got '{openapi_version}' "
                        f"(function '{logical_name}')."
                    )

                if has_querystring:
                    qs_media_type = meta.get(
                        "querystring_media_type", "application/x-www-form-urlencoded"
                    )
                    if qs_model is not None:
                        qs_resolved = model_to_schema(qs_model, components)
                    else:
                        qs_resolved = hoist_inline_defs(
                            qs_schema, components, hoist_flat=hoist_flat_schemas
                        )
                    qs_param = {
                        "in": "querystring",
                        "content": {qs_media_type: {"schema": qs_resolved}},
                    }
                    if op_parameters is None:
                        op_parameters = []
                    op_parameters.append(qs_param)

                # Validation: querystring must not coexist with 'query' params,
                # and at most one querystring parameter may appear per operation.
                if op_parameters:
                    has_query_param = any(
                        isinstance(p, dict) and p.get("in") == "query"
                        for p in op_parameters
                    )
                    qs_total = sum(
                        1
                        for p in op_parameters
                        if isinstance(p, dict) and p.get("in") == "querystring"
                    )
                    if qs_total > 1:
                        raise OpenAPISpecConfigError(
                            f"Operation for '{logical_name}' declares multiple "
                            f"'querystring' parameters; at most one is allowed."
                        )
                    if qs_total and has_query_param:
                        raise OpenAPISpecConfigError(
                            f"Operation for '{logical_name}' mixes 'query' and "
                            f"'querystring' parameters, which OpenAPI 3.2 forbids."
                        )

                # security --------------------------------------------------------
                security: list[dict[str, list[str]]] = meta.get("security", [])
                # Infer from auth_level only when the operation declares no
                # explicit security (user-declared security always wins) and the
                # opt-in flag is set (#482). The binding-captured ``_auth_level``
                # is only present on the FunctionApp-scan path.
                if infer_auth_level and not security:
                    _inferred = _infer_auth_security(meta.get("_auth_level"))
                    if _inferred is not None:
                        security = _inferred[0]

                # requestBody schema (POST/PUT/PATCH/DELETE) ----------------------
                request_body_obj: dict[str, Any] | None = None
                required = meta.get("request_body_required", True)
                if meta.get("request_body"):
                    request_body_obj = {
                        "required": required,
                        "content": {
                            "application/json": {
                                "schema": hoist_inline_defs(
                                    meta["request_body"],
                                    components,
                                    hoist_flat=hoist_flat_schemas,
                                )
                            }
                        },
                    }
                elif meta.get("request_model"):
                    try:
                        request_body_obj = {
                            "required": required,
                            "content": {
                                "application/json": {
                                    "schema": model_to_schema(meta["request_model"], components)
                                }
                            },
                        }
                    except Exception as e:
                        logger.warning(
                            f"Failed to generate request schema for {func_name}: {str(e)}"
                        )
                        request_body_obj = {
                            "required": required,
                            "content": {"application/json": {"schema": {"type": "object"}}},
                        }

                for method in methods_to_emit:
                    # operation object --------------------------------------------
                    op: dict[str, Any] = {
                        "summary": meta.get("summary", ""),
                        "description": meta.get("description", ""),
                        "operationId": _operation_id_for(
                            meta.get("operation_id"), method, logical_name, methods_expanded
                        ),
                        "tags": meta.get("tags") or ["default"],
                        "responses": copy.deepcopy(responses),
                    }
                    if op_parameters is not None:
                        op["parameters"] = copy.deepcopy(op_parameters)
                    if security:
                        op["security"] = security

                    # requestBody: only body-bearing methods, and never on an
                    # auto-expanded GET/HEAD/DELETE (OpenAPI leaves the body
                    # undefined there and many tools reject it). ``query`` (3.2)
                    # is safe/idempotent but explicitly carries a request
                    # payload, so it is body-bearing too.
                    body_methods = {"post", "put", "patch", "delete", "query"}
                    if methods_expanded:
                        body_methods -= BODYLESS_HTTP_METHODS
                    if request_body_obj is not None and method in body_methods:
                        op["requestBody"] = copy.deepcopy(request_body_obj)

                    # merge into paths — detect duplicate path+method registrations
                    path_item = paths.setdefault(path, {})
                    if method in path_item:
                        _dup_msg = (
                            f"Duplicate operation: {method.upper()} {path} — "
                            "only the last @openapi registration will appear in the spec"
                        )
                        if strict:
                            raise OpenAPISpecConfigError(_dup_msg)
                        logger.warning("OpenAPI spec: %s", _dup_msg)
                        _dup_registry = registry if registry is not None else _default_registry
                        _dup_registry.add_duplicate_operation(method, path)
                    path_item[method] = op

            except OpenAPISpecConfigError:
                # Configuration contract violations (e.g. querystring misuse)
                # must always surface, regardless of strict mode.
                raise
            except (KeyError, TypeError, ValueError):
                if strict:
                    logger.error("Failed to process function %s (strict mode)", func_name)
                    raise
                logger.exception("Failed to process function %s", func_name)
                continue

        spec: dict[str, Any] = {
            "openapi": openapi_version,
            "info": {
                "title": title,
                "version": version,
                "description": description,
            },
            "paths": paths,
        }

        if openapi_version in (OPENAPI_VERSION_3_1, OPENAPI_VERSION_3_2):
            spec["info"]["summary"] = title
            _convert_operation_schemas_to_3_1(paths)
        elif openapi_version == OPENAPI_VERSION_3_0:
            # Down-convert path-level inline schemas (inferred and explicit
            # ``responses=``/``requests=``) so nested Pydantic nullability is
            # emitted as valid 3.0 ``nullable: true`` rather than the 3.1-only
            # ``anyOf: [T, {type: null}]`` idiom (#562).
            _convert_operation_schemas_to_3_0(paths)

        # Top-level and info metadata passthrough (#494). Each field is emitted
        # only when supplied; contact/license nest under ``info`` while
        # servers/externalDocs/tags sit at the document root.
        if contact is not None:
            spec["info"]["contact"] = contact
        if license is not None:
            spec["info"]["license"] = license
        if servers is not None:
            spec["servers"] = servers
        if external_docs is not None:
            spec["externalDocs"] = external_docs
        if tags is not None:
            spec["tags"] = tags

        # Merge security schemes: explicit param + per-operation schemes from registry.
        # Raises OpenAPISpecConfigError on collision (same name, different definition).
        all_security_schemes: dict[str, dict[str, Any]] = {}
        if security_schemes:
            all_security_schemes.update(security_schemes)
        for _fn, meta in registry_entries.items():
            scheme = meta.get("security_scheme")
            if isinstance(scheme, dict):
                for name, definition in scheme.items():
                    if name in all_security_schemes and all_security_schemes[name] != definition:
                        raise OpenAPISpecConfigError(
                            f"Conflicting security scheme definition for '{name}': "
                            f"existing={all_security_schemes[name]!r}, "
                            f"new={definition!r}"
                        )
                    all_security_schemes[name] = definition
            # Add the inferred Azure function-key scheme for operations that
            # relied on auth_level inference (#482). Only when the operation
            # declared neither explicit security nor an explicit scheme, and
            # only if the name is free — a user scheme of the same name always
            # wins (no collision error is raised for the inferred default).
            if (
                infer_auth_level
                and not meta.get("security")
                and not meta.get("security_scheme")
            ):
                _inferred = _infer_auth_security(meta.get("_auth_level"))
                if _inferred is not None:
                    for name, definition in _inferred[1].items():
                        all_security_schemes.setdefault(name, definition)

        if all_security_schemes:
            components["securitySchemes"] = all_security_schemes

        if components.get("schemas"):
            if openapi_version in (OPENAPI_VERSION_3_1, OPENAPI_VERSION_3_2):
                components["schemas"] = _convert_schemas_to_3_1(components["schemas"])
            elif openapi_version == OPENAPI_VERSION_3_0:
                # Down-convert nullable component schemas to valid 3.0 form
                # (#562) before the compatibility audit, so faithfully
                # convertible nullability no longer trips the warn/strict path.
                components["schemas"] = _convert_schemas_to_3_0(components["schemas"])
                compat_warnings = _check_schemas_3_0_compatible(components["schemas"], strict)
                compat_warnings = _check_schemas_3_0_compatible(components["schemas"], strict)
                for w in compat_warnings:
                    logger.warning("OpenAPI 3.0 compatibility: %s", w)
        if components.get("schemas") or components.get("securitySchemes"):
            spec["components"] = components

        spec = _normalize_spec_output(spec)

        validation_warnings = _validate_spec(spec)
        # Custom (non-standard) HTTP methods are validated above as ordinary
        # operations, then relocated: under 3.2 into each path item's
        # ``additionalOperations`` map, and under 3.0/3.1 dropped (the format has
        # no way to express them) with a warning.
        # Custom-method restructuring and query removal are the two constructs
        # that vanish on a pre-3.2 downgrade. Record them on the registry's
        # downgrade-drop channel so ``collect_spec_warnings`` / ``--fail-on-warnings``
        # can observe silent API-contract loss (#479), in addition to logging.
        downgrade_drops = _restructure_additional_operations(spec, openapi_version)
        downgrade_drops.extend(_drop_unsupported_query(spec, openapi_version))
        validation_warnings.extend(downgrade_drops)
        for drop in downgrade_drops:
            _diag_registry.add_downgrade_drop(drop)
        for warning in validation_warnings:
            logger.warning("OpenAPI spec validation: %s", warning)

        if strict and validation_warnings:
            raise OpenAPISpecConfigError(
                "Strict mode: generated spec has validation errors:\n"
                + "\n".join(f"  - {w}" for w in validation_warnings)
            )

        logger.info(
            f"Generated OpenAPI {openapi_version} spec with {len(paths)} paths "
            f"for {len(registry_entries)} functions"
        )
        return spec

    except OpenAPISpecConfigError:
        raise
    except Exception as e:
        if strict and isinstance(e, (KeyError, TypeError, ValueError)):
            raise
        logger.error(f"Failed to generate OpenAPI specification: {str(e)}")
        raise RuntimeError("Failed to generate OpenAPI specification") from e

get_openapi_json

Return the spec as pretty-printed JSON (UTF-8).

Parameters:

Name Type Description Default
title str

API title

'API'
version str

API version

'1.0.0'
openapi_version str

OpenAPI specification version ("3.0.0", "3.1.0", or "3.2.0")

OPENAPI_VERSION_3_1
description str

Description for the OpenAPI info object

DEFAULT_OPENAPI_INFO_DESCRIPTION
security_schemes dict[str, dict[str, Any]] | None

Security scheme definitions for components.securitySchemes.

None
route_prefix str

HTTP route prefix from host.json (extensions.http.routePrefix). Defaults to "/api". Pass "" for hosts that disable the prefix or a custom value such as "/v1".

DEFAULT_ROUTE_PREFIX
strict bool

When True, raise on any registry entry processing failure.

False
registry OpenAPIRegistry | None

Inject a custom :class:OpenAPIRegistry instead of the shared global one. Defaults to None (the process-wide registry).

None
hoist_flat_schemas bool

When True (opt-in, #375), structured flat schemas are promoted into components.schemas. Defaults to False to preserve the existing generated spec shape.

False
infer_auth_level bool

When True (opt-in, #482), derive OpenAPI security from each operation's Azure Functions auth_level. Defaults to False. See :func:generate_openapi_spec for details.

False

Returns:

Type Description
str

OpenAPI spec in JSON format.

Source code in src/azure_functions_openapi/spec.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 = DEFAULT_ROUTE_PREFIX,
    strict: bool = False,
    registry: OpenAPIRegistry | None = None,
    hoist_flat_schemas: bool = False,
    infer_auth_level: bool = False,
) -> str:
    """Return the spec as pretty-printed JSON (UTF-8).

    Parameters:
        title: API title
        version: API version
        openapi_version: OpenAPI specification version ("3.0.0", "3.1.0", or "3.2.0")
        description: Description for the OpenAPI info object
        security_schemes: Security scheme definitions for components.securitySchemes.
        route_prefix: HTTP route prefix from ``host.json``
            (``extensions.http.routePrefix``). Defaults to ``"/api"``. Pass
            ``""`` for hosts that disable the prefix or a custom value such
            as ``"/v1"``.
        strict: When ``True``, raise on any registry entry processing failure.
        registry: Inject a custom :class:`OpenAPIRegistry` instead of the shared
            global one. Defaults to ``None`` (the process-wide registry).
        hoist_flat_schemas: When ``True`` (opt-in, #375), structured flat
            schemas are promoted into ``components.schemas``. Defaults to
            ``False`` to preserve the existing generated spec shape.
        infer_auth_level: When ``True`` (opt-in, #482), derive OpenAPI security
            from each operation's Azure Functions ``auth_level``. Defaults to
            ``False``. See :func:`generate_openapi_spec` for details.

    Returns:
        OpenAPI spec in JSON format.
    """
    try:
        spec = generate_openapi_spec(
            title,
            version,
            openapi_version,
            description=description,
            security_schemes=security_schemes,
            route_prefix=route_prefix,
            strict=strict,
            hoist_flat_schemas=hoist_flat_schemas,
            infer_auth_level=infer_auth_level,
            registry=registry,
        )
        return json.dumps(spec, indent=2, ensure_ascii=False)
    except OpenAPISpecConfigError:
        raise
    except Exception as e:
        logger.error(f"Failed to generate OpenAPI JSON: {str(e)}")
        raise RuntimeError("Failed to generate OpenAPI JSON") from e

get_openapi_yaml

Return the spec as YAML.

Parameters:

Name Type Description Default
title str

API title

'API'
version str

API version

'1.0.0'
openapi_version str

OpenAPI specification version ("3.0.0", "3.1.0", or "3.2.0")

OPENAPI_VERSION_3_1
description str

Description for the OpenAPI info object

DEFAULT_OPENAPI_INFO_DESCRIPTION
security_schemes dict[str, dict[str, Any]] | None

Security scheme definitions for components.securitySchemes.

None
route_prefix str

HTTP route prefix from host.json (extensions.http.routePrefix). Defaults to "/api". Pass "" for hosts that disable the prefix or a custom value such as "/v1".

DEFAULT_ROUTE_PREFIX
strict bool

When True, raise on any registry entry processing failure.

False
registry OpenAPIRegistry | None

Inject a custom :class:OpenAPIRegistry instead of the shared global one. Defaults to None (the process-wide registry).

None
hoist_flat_schemas bool

When True (opt-in, #375), structured flat schemas are promoted into components.schemas. Defaults to False to preserve the existing generated spec shape.

False
infer_auth_level bool

When True (opt-in, #482), derive OpenAPI security from each operation's Azure Functions auth_level. Defaults to False. See :func:generate_openapi_spec for details.

False

Returns:

Type Description
str

OpenAPI spec in YAML format.

Source code in src/azure_functions_openapi/spec.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 = DEFAULT_ROUTE_PREFIX,
    strict: bool = False,
    registry: OpenAPIRegistry | None = None,
    hoist_flat_schemas: bool = False,
    infer_auth_level: bool = False,
) -> str:
    """Return the spec as YAML.

    Parameters:
        title: API title
        version: API version
        openapi_version: OpenAPI specification version ("3.0.0", "3.1.0", or "3.2.0")
        description: Description for the OpenAPI info object
        security_schemes: Security scheme definitions for components.securitySchemes.
        route_prefix: HTTP route prefix from ``host.json``
            (``extensions.http.routePrefix``). Defaults to ``"/api"``. Pass
            ``""`` for hosts that disable the prefix or a custom value such
            as ``"/v1"``.
        strict: When ``True``, raise on any registry entry processing failure.
        registry: Inject a custom :class:`OpenAPIRegistry` instead of the shared
            global one. Defaults to ``None`` (the process-wide registry).
        hoist_flat_schemas: When ``True`` (opt-in, #375), structured flat
            schemas are promoted into ``components.schemas``. Defaults to
            ``False`` to preserve the existing generated spec shape.
        infer_auth_level: When ``True`` (opt-in, #482), derive OpenAPI security
            from each operation's Azure Functions ``auth_level``. Defaults to
            ``False``. See :func:`generate_openapi_spec` for details.

    Returns:
        OpenAPI spec in YAML format.
    """
    try:
        spec = generate_openapi_spec(
            title,
            version,
            openapi_version,
            description=description,
            security_schemes=security_schemes,
            route_prefix=route_prefix,
            strict=strict,
            hoist_flat_schemas=hoist_flat_schemas,
            infer_auth_level=infer_auth_level,
            registry=registry,
        )
        return yaml.safe_dump(spec, sort_keys=False, allow_unicode=True)
    except OpenAPISpecConfigError:
        raise
    except Exception as e:
        logger.error(f"Failed to generate OpenAPI YAML: {str(e)}")
        raise RuntimeError("Failed to generate OpenAPI YAML") from e

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 or 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="X-XSS-Protection" content="1; mode=block">
        <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'],
            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",
        "X-XSS-Protection": "1; mode=block",
        "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

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.

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)
    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; to_dict() for JSON
WarningCode str-based enum of stable codes: version-skew, ambiguous-namespace, duplicate-operation, spec-validation, discovery-skipped, empty-discovery, method-binding-mismatch

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.