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 | |
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 |
DEFAULT_ROUTE_PREFIX
|
strict
|
bool
|
When |
False
|
hoist_flat_schemas
|
bool
|
When |
False
|
infer_auth_level
|
bool
|
When |
False
|
servers
|
list[dict[str, Any]] | None
|
Optional list of OpenAPI Server Objects emitted at the
document's top-level |
None
|
contact
|
dict[str, Any] | None
|
Optional Contact Object merged into |
None
|
license
|
dict[str, Any] | None
|
Optional License Object merged into |
None
|
external_docs
|
dict[str, Any] | None
|
Optional External Documentation Object emitted at the
document's top-level |
None
|
tags
|
list[dict[str, Any]] | None
|
Optional list of top-level Tag Objects emitted at the document's
|
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 | |
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 |
DEFAULT_ROUTE_PREFIX
|
strict
|
bool
|
When |
False
|
registry
|
OpenAPIRegistry | None
|
Inject a custom :class: |
None
|
hoist_flat_schemas
|
bool
|
When |
False
|
infer_auth_level
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
str
|
OpenAPI spec in JSON format. |
Source code in src/azure_functions_openapi/spec.py
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 |
DEFAULT_ROUTE_PREFIX
|
strict
|
bool
|
When |
False
|
registry
|
OpenAPIRegistry | None
|
Inject a custom :class: |
None
|
hoist_flat_schemas
|
bool
|
When |
False
|
infer_auth_level
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
str
|
OpenAPI spec in YAML format. |
Source code in src/azure_functions_openapi/spec.py
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
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | |
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 |
Related internals¶
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.