Core Modules¶
This section provides documentation for the core components of Flask-X-OpenAPI-Schema.
Configuration¶
Configuration management for OpenAPI schema generation.
This module provides configuration classes and utilities for managing parameter prefixes and other settings for OpenAPI schema generation.
Includes classes for managing conventional parameter prefixes, caching behavior, and OpenAPI schema generation settings, along with thread-safe global configuration.
CacheConfig
dataclass
¶
Configuration class for caching behavior.
This class holds configuration settings for controlling cache behavior in the library.
Attributes:
Name | Type | Description |
---|---|---|
enabled |
bool
|
Global flag to enable/disable function metadata caching (default: True) |
Source code in src/flask_x_openapi_schema/core/config.py
ConventionalPrefixConfig
dataclass
¶
Configuration class for OpenAPI parameter prefixes.
This class holds configuration settings for parameter prefixes used in binding request data to function parameters.
Attributes:
Name | Type | Description |
---|---|---|
request_body_prefix |
str
|
Prefix for request body parameters (default: "_x_body") |
request_query_prefix |
str
|
Prefix for query parameters (default: "_x_query") |
request_path_prefix |
str
|
Prefix for path parameters (default: "_x_path") |
request_file_prefix |
str
|
Prefix for file parameters (default: "_x_file") |
extra_options |
dict[str, Any]
|
Additional configuration options |
Examples:
>>> from flask_x_openapi_schema import ConventionalPrefixConfig
>>> config = ConventionalPrefixConfig(
... request_body_prefix="req_body",
... request_query_prefix="req_query",
... request_path_prefix="req_path",
... request_file_prefix="req_file",
... )
Source code in src/flask_x_openapi_schema/core/config.py
OpenAPIConfig
dataclass
¶
Configuration class for OpenAPI schema generation.
This class holds configuration settings for OpenAPI schema generation.
Attributes:
Name | Type | Description |
---|---|---|
title |
str
|
API title |
version |
str
|
API version |
description |
str
|
API description |
prefix_config |
ConventionalPrefixConfig
|
Parameter prefix configuration |
security_schemes |
dict[str, dict[str, Any]]
|
Security schemes configuration |
openapi_version |
str
|
OpenAPI specification version |
servers |
list[dict[str, Any]]
|
List of server objects |
external_docs |
dict[str, Any] | None
|
External documentation |
webhooks |
dict[str, dict[str, Any]]
|
Webhook definitions |
json_schema_dialect |
str | None
|
JSON Schema dialect |
cache_config |
CacheConfig
|
Configuration for caching behavior |
Source code in src/flask_x_openapi_schema/core/config.py
ThreadSafeConfig
¶
Thread-safe configuration holder.
This class provides thread-safe access to configuration settings.
Source code in src/flask_x_openapi_schema/core/config.py
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 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 |
|
get()
¶
Get the current prefix configuration.
Returns:
Name | Type | Description |
---|---|---|
ConventionalPrefixConfig |
ConventionalPrefixConfig
|
Current prefix configuration |
Source code in src/flask_x_openapi_schema/core/config.py
get_cache_config()
¶
Get the current cache configuration.
Returns:
Name | Type | Description |
---|---|---|
CacheConfig |
CacheConfig
|
Current cache configuration |
Source code in src/flask_x_openapi_schema/core/config.py
get_openapi_config()
¶
Get the current OpenAPI configuration.
Returns:
Name | Type | Description |
---|---|---|
OpenAPIConfig |
OpenAPIConfig
|
Current OpenAPI configuration |
Source code in src/flask_x_openapi_schema/core/config.py
reset()
¶
Reset to default prefix configuration.
Returns:
Type | Description |
---|---|
None
|
None |
Source code in src/flask_x_openapi_schema/core/config.py
reset_all()
¶
Reset all configurations to defaults.
Returns:
Type | Description |
---|---|
None
|
None |
Source code in src/flask_x_openapi_schema/core/config.py
set(config)
¶
Set a new prefix configuration.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
config
|
ConventionalPrefixConfig
|
New prefix configuration |
required |
Source code in src/flask_x_openapi_schema/core/config.py
set_cache_config(config)
¶
Set a new cache configuration.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
config
|
CacheConfig
|
New cache configuration |
required |
Source code in src/flask_x_openapi_schema/core/config.py
set_openapi_config(config)
¶
Set a new OpenAPI configuration.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
config
|
OpenAPIConfig
|
New OpenAPI configuration |
required |
Source code in src/flask_x_openapi_schema/core/config.py
configure_cache(config)
¶
Configure global cache settings.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
config
|
CacheConfig
|
Configuration object with cache settings |
required |
Examples:
>>> from flask_x_openapi_schema import CacheConfig, configure_cache
>>> cache_config = CacheConfig(enabled=True)
>>> configure_cache(cache_config)
Source code in src/flask_x_openapi_schema/core/config.py
configure_openapi(config)
¶
Configure global OpenAPI settings.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
config
|
OpenAPIConfig
|
Configuration object with OpenAPI settings |
required |
Source code in src/flask_x_openapi_schema/core/config.py
configure_prefixes(config)
¶
Configure global parameter prefixes.
Sets the global configuration for parameter prefixes used in binding request data to function parameters. This affects all decorators that don't specify their own prefix configuration.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
config
|
ConventionalPrefixConfig
|
Configuration object with parameter prefixes |
required |
Examples:
>>> from flask_x_openapi_schema import ConventionalPrefixConfig, configure_prefixes
>>> custom_config = ConventionalPrefixConfig(request_body_prefix="req_body", request_query_prefix="req_query")
>>> configure_prefixes(custom_config)
Source code in src/flask_x_openapi_schema/core/config.py
get_cache_config()
¶
Get the current cache configuration.
Returns:
Name | Type | Description |
---|---|---|
CacheConfig |
CacheConfig
|
Current cache configuration |
get_openapi_config()
¶
Get the current OpenAPI configuration.
Returns:
Name | Type | Description |
---|---|---|
OpenAPIConfig |
OpenAPIConfig
|
Current OpenAPI configuration |
reset_all_config()
¶
Reset all configuration to default values.
Resets all configuration settings to their default values, including parameter prefixes, OpenAPI settings, and cache configuration.
Source code in src/flask_x_openapi_schema/core/config.py
reset_prefixes()
¶
Reset parameter prefixes to default values.
Resets the global parameter prefix configuration to the default values: - request_body_prefix: "_x_body" - request_query_prefix: "_x_query" - request_path_prefix: "_x_path" - request_file_prefix: "_x_file"
Examples:
>>> from flask_x_openapi_schema import reset_prefixes
>>> reset_prefixes() # Resets to default prefixes
Source code in src/flask_x_openapi_schema/core/config.py
Cache¶
Simplified caching mechanism for OpenAPI schema generation.
This module provides a minimal caching system focused only on the essential caching needs for the @openapi_metadata decorator. It uses WeakKeyDictionary to avoid memory leaks when functions are garbage collected.
Cache Types
- WeakKeyDictionary: For function metadata to avoid memory leaks
Thread Safety
This module is designed to be thread-safe for use in multi-threaded web servers.
clear_all_caches()
¶
Clear all caches to free memory or force regeneration.
This function clears the function metadata cache.
get_parameter_prefixes(config=None)
¶
Get parameter prefixes from config or global defaults.
This function retrieves parameter prefixes from the provided config or global defaults.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
config
|
Any | None
|
Optional configuration object with custom prefixes |
None
|
Returns:
Type | Description |
---|---|
tuple[str, str, str, str]
|
Tuple of (body_prefix, query_prefix, path_prefix, file_prefix) |
Source code in src/flask_x_openapi_schema/core/cache.py
Decorator Base¶
Base classes and utilities for OpenAPI metadata decorators.
This module provides the core functionality for creating OpenAPI metadata decorators that can be used with Flask and Flask-RESTful applications. It includes utilities for parameter extraction, metadata generation, and request processing.
The main classes are: - OpenAPIDecoratorBase: Serves as the foundation for framework-specific decorator implementations. It handles parameter binding, metadata caching, and OpenAPI schema generation. - DecoratorBase: A base class for framework-specific decorators that encapsulates common functionality for processing request bodies, query parameters, and path parameters.
DecoratorBase
¶
Bases: ABC
Base class for framework-specific decorators.
This class encapsulates common functionality for processing request bodies, query parameters, and path parameters. It is designed to be inherited by framework-specific decorator implementations.
Attributes:
Name | Type | Description |
---|---|---|
summary |
str or I18nStr
|
Short summary of the endpoint. |
description |
str or I18nStr
|
Detailed description of the endpoint. |
tags |
list
|
List of tags to categorize the endpoint. |
operation_id |
str
|
Unique identifier for the operation. |
responses |
OpenAPIMetaResponse
|
Response models configuration. |
deprecated |
bool
|
Whether the endpoint is deprecated. |
security |
list
|
Security requirements for the endpoint. |
external_docs |
dict
|
External documentation references. |
language |
str
|
Language code to use for I18nStr values. |
prefix_config |
ConventionalPrefixConfig
|
Configuration for parameter prefixes. |
content_type |
str
|
Custom content type for request body. |
request_content_types |
RequestContentTypes
|
Multiple content types for request body. |
response_content_types |
ResponseContentTypes
|
Multiple content types for response body. |
content_type_resolver |
Callable
|
Function to determine content type based on request. |
default_error_response |
Type[BaseErrorResponse]
|
Default error response class. |
Source code in src/flask_x_openapi_schema/core/decorator_base.py
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 |
|
__call__(func)
abstractmethod
¶
Apply the decorator to the function.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
func
|
Callable
|
The function to decorate |
required |
Returns:
Type | Description |
---|---|
Callable
|
The decorated function |
Source code in src/flask_x_openapi_schema/core/decorator_base.py
__init__(summary=None, description=None, tags=None, operation_id=None, responses=None, deprecated=False, security=None, external_docs=None, language=None, prefix_config=None, content_type=None, request_content_types=None, response_content_types=None, content_type_resolver=None)
¶
Initialize the decorator with OpenAPI metadata parameters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
summary
|
str | I18nStr | None
|
Short summary of the endpoint, can be an I18nStr for localization. |
None
|
description
|
str | I18nStr | None
|
Detailed description of the endpoint, can be an I18nStr. |
None
|
tags
|
list[str] | None
|
List of tags to categorize the endpoint. |
None
|
operation_id
|
str | None
|
Unique identifier for the operation. |
None
|
responses
|
OpenAPIMetaResponse | None
|
Response models configuration. |
None
|
deprecated
|
bool
|
Whether the endpoint is deprecated. Defaults to False. |
False
|
security
|
list[dict[str, list[str]]] | None
|
Security requirements for the endpoint. |
None
|
external_docs
|
dict[str, str] | None
|
External documentation references. |
None
|
language
|
str | None
|
Language code to use for I18nStr values. |
None
|
prefix_config
|
ConventionalPrefixConfig | None
|
Configuration for parameter prefixes. |
None
|
content_type
|
str | None
|
Custom content type for request body. If None, will be auto-detected. |
None
|
request_content_types
|
RequestContentTypes | None
|
Multiple content types for request body. |
None
|
response_content_types
|
ResponseContentTypes | None
|
Multiple content types for response body. |
None
|
content_type_resolver
|
Callable[[Any], str] | None
|
Function to determine content type based on request. |
None
|
Source code in src/flask_x_openapi_schema/core/decorator_base.py
extract_parameters_from_models(query_model, path_params)
¶
Extract OpenAPI parameters from models.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
query_model
|
type[BaseModel] | None
|
The query parameter model |
required |
path_params
|
list[str] | None
|
List of path parameter names |
required |
Returns:
Type | Description |
---|---|
list[dict[str, Any]]
|
List of OpenAPI parameter objects |
Source code in src/flask_x_openapi_schema/core/decorator_base.py
process_additional_params(kwargs, param_names)
¶
Process additional framework-specific parameters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
kwargs
|
dict[str, Any]
|
The keyword arguments to update |
required |
param_names
|
list[str]
|
List of parameter names that have been processed |
required |
Returns:
Type | Description |
---|---|
dict[str, Any]
|
Updated kwargs dictionary |
Source code in src/flask_x_openapi_schema/core/decorator_base.py
process_query_params(param_name, model, kwargs)
abstractmethod
¶
Process query parameters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
param_name
|
str
|
The parameter name to bind the model instance to |
required |
model
|
type[BaseModel]
|
The Pydantic model class to use for validation |
required |
kwargs
|
dict[str, Any]
|
The keyword arguments to update |
required |
Returns:
Type | Description |
---|---|
dict[str, Any]
|
Updated kwargs dictionary with the model instance |
Source code in src/flask_x_openapi_schema/core/decorator_base.py
process_request_body(param_name, model, kwargs)
¶
Process request body parameters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
param_name
|
str
|
The parameter name to bind the model instance to |
required |
model
|
type[BaseModel]
|
The Pydantic model class to use for validation |
required |
kwargs
|
dict[str, Any]
|
The keyword arguments to update |
required |
Returns:
Type | Description |
---|---|
dict[str, Any]
|
Updated kwargs dictionary with the model instance |
Source code in src/flask_x_openapi_schema/core/decorator_base.py
OpenAPIDecoratorBase
¶
Base class for OpenAPI metadata decorators.
This class provides the foundation for framework-specific OpenAPI metadata decorators. It handles parameter extraction, metadata generation, and request processing in a framework-agnostic way, delegating framework-specific operations to subclasses.
The decorator adds OpenAPI metadata to API endpoint functions and handles parameter binding between HTTP requests and function parameters based on naming conventions.
Attributes:
Name | Type | Description |
---|---|---|
summary |
str or I18nStr
|
Short summary of the endpoint. |
description |
str or I18nStr
|
Detailed description of the endpoint. |
tags |
list
|
List of tags to categorize the endpoint. |
operation_id |
str
|
Unique identifier for the operation. |
responses |
OpenAPIMetaResponse
|
Response models configuration. |
deprecated |
bool
|
Whether the endpoint is deprecated. |
security |
list
|
Security requirements for the endpoint. |
external_docs |
dict
|
External documentation references. |
language |
str
|
Language code to use for I18nStr values. |
prefix_config |
ConventionalPrefixConfig
|
Configuration for parameter prefixes. |
framework |
str
|
Framework name ('flask' or 'flask_restful'). |
framework_decorator |
Framework-specific decorator instance. |
Source code in src/flask_x_openapi_schema/core/decorator_base.py
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 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 |
|
__call__(func)
¶
Apply the decorator to the function.
This method has been refactored to use smaller, more focused methods.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
func
|
Callable[P, R]
|
The function to decorate |
required |
Returns:
Type | Description |
---|---|
Callable[P, R]
|
The decorated function |
Source code in src/flask_x_openapi_schema/core/decorator_base.py
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 |
|
__init__(summary=None, description=None, tags=None, operation_id=None, responses=None, deprecated=False, security=None, external_docs=None, language=None, prefix_config=None, framework='flask', content_type=None, request_content_types=None, response_content_types=None, content_type_resolver=None)
¶
Initialize the decorator with OpenAPI metadata parameters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
summary
|
str | I18nStr | None
|
Short summary of the endpoint, can be an I18nStr for localization. |
None
|
description
|
str | I18nStr | None
|
Detailed description of the endpoint, can be an I18nStr. |
None
|
tags
|
list[str] | None
|
List of tags to categorize the endpoint. |
None
|
operation_id
|
str | None
|
Unique identifier for the operation. |
None
|
responses
|
OpenAPIMetaResponse | None
|
Response models configuration. |
None
|
deprecated
|
bool
|
Whether the endpoint is deprecated. Defaults to False. |
False
|
security
|
list[dict[str, list[str]]] | None
|
Security requirements for the endpoint. |
None
|
external_docs
|
dict[str, str] | None
|
External documentation references. |
None
|
language
|
str | None
|
Language code to use for I18nStr values. |
None
|
prefix_config
|
ConventionalPrefixConfig | None
|
Configuration for parameter prefixes. |
None
|
framework
|
str
|
Framework name ('flask' or 'flask_restful'). Defaults to "flask". |
'flask'
|
content_type
|
str | None
|
Custom content type for request body. If None, will be auto-detected. |
None
|
request_content_types
|
RequestContentTypes | None
|
Multiple content types for request body. |
None
|
response_content_types
|
ResponseContentTypes | None
|
Multiple content types for response body. |
None
|
content_type_resolver
|
Callable[[Any], str] | None
|
Function to determine content type based on request. |
None
|
Source code in src/flask_x_openapi_schema/core/decorator_base.py
Schema Generator¶
OpenAPI Schema Generator for API documentation.
This module provides the main class for generating OpenAPI schemas from Flask-RESTful resources. It handles scanning resources, extracting metadata, and generating a complete OpenAPI schema.
OpenAPISchemaGenerator
¶
Generator for OpenAPI schemas from Flask-RESTful resources.
This class scans Flask-RESTful resources and generates OpenAPI schemas based on the resource methods, docstrings, and type annotations.
Source code in src/flask_x_openapi_schema/core/schema_generator.py
28 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 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 |
|
__init__(title=None, version=None, description=None, language=None)
¶
Initialize the OpenAPI schema generator.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
title
|
str | None
|
The title of the API (default: from config) |
None
|
version
|
str | None
|
The version of the API (default: from config) |
None
|
description
|
str | None
|
The description of the API (default: from config) |
None
|
language
|
str | None
|
The language to use for internationalized strings (default: current language) |
None
|
Source code in src/flask_x_openapi_schema/core/schema_generator.py
add_security_scheme(name, scheme)
¶
Add a security scheme to the OpenAPI schema.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
The name of the security scheme |
required |
scheme
|
dict[str, Any]
|
The security scheme definition |
required |
Source code in src/flask_x_openapi_schema/core/schema_generator.py
add_tag(name, description='')
¶
Add a tag to the OpenAPI schema.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
The name of the tag |
required |
description
|
str
|
The description of the tag |
''
|
Source code in src/flask_x_openapi_schema/core/schema_generator.py
add_webhook(name, webhook_data)
¶
Add a webhook to the OpenAPI schema.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
The name of the webhook |
required |
webhook_data
|
dict[str, Any]
|
The webhook definition |
required |
Source code in src/flask_x_openapi_schema/core/schema_generator.py
generate_schema()
¶
Generate the complete OpenAPI schema.
Returns:
Type | Description |
---|---|
dict[str, Any]
|
The OpenAPI schema as a dictionary |
Source code in src/flask_x_openapi_schema/core/schema_generator.py
scan_blueprint(blueprint)
¶
Scan a Flask blueprint for API resources and add them to the schema.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
blueprint
|
Blueprint
|
The Flask blueprint to scan |
required |
Source code in src/flask_x_openapi_schema/core/schema_generator.py
Utilities¶
Utility functions for OpenAPI schema generation.
This module provides utility functions for converting Pydantic models to OpenAPI schemas, handling references, and processing internationalized strings. It includes functions for:
- Converting Pydantic models to OpenAPI schemas
- Converting Python types to OpenAPI types
- Generating response schemas for API endpoints
- Processing internationalized strings in schemas
clear_i18n_cache()
¶
Clear the i18n processing cache.
Clears any cached results from I18n string processing functions. Call this function when you need to ensure that I18n strings are re-processed, such as after changing the language configuration.
Source code in src/flask_x_openapi_schema/core/utils.py
clear_references_cache()
¶
Clear the references processing cache.
Clears any cached results from schema reference processing functions. Call this function when you need to ensure that schema references are re-processed, such as after modifying schema definitions.
Source code in src/flask_x_openapi_schema/core/utils.py
error_response_schema(description, status_code=400)
¶
Generate an OpenAPI error response schema.
Creates a simple OpenAPI error response object with a description. Unlike success responses, error responses don't include content schema.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
description
|
str
|
Description of the error |
required |
status_code
|
int | str
|
HTTP status code for the error (default: 400) |
400
|
Returns:
Name | Type | Description |
---|---|---|
dict |
dict[str, Any]
|
An OpenAPI error response schema object |
Examples:
>>> schema = error_response_schema("Bad Request", 400)
>>> schema["400"]["description"]
'Bad Request'
Source code in src/flask_x_openapi_schema/core/utils.py
process_i18n_dict(data, language)
¶
Process a dictionary that might contain I18nString values.
Recursively processes all I18nString values in a dictionary, converting them to language-specific strings. Also handles nested dictionaries and lists that might contain I18nString values.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data
|
dict[str, Any]
|
The dictionary to process, which might contain I18nString values |
required |
language
|
str
|
The language code to use for extracting localized strings |
required |
Returns:
Name | Type | Description |
---|---|---|
dict |
dict[str, Any]
|
A new dictionary with I18nString values converted to language-specific strings |
Examples:
>>> from flask_x_openapi_schema.i18n.i18n_string import I18nStr
>>> data = {
... "title": I18nStr({"en": "Hello", "fr": "Bonjour"}),
... "nested": {"subtitle": I18nStr({"en": "World", "fr": "Monde"})},
... }
>>> result = process_i18n_dict(data, "en")
>>> result["title"]
'Hello'
>>> result["nested"]["subtitle"]
'World'
Source code in src/flask_x_openapi_schema/core/utils.py
process_i18n_value(value, language)
¶
Process a value that might be an I18nString or contain I18nString values.
Recursively processes values that might be I18nString instances or contain I18nString instances (in lists or dictionaries). For I18nString instances, returns the string for the specified language.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value
|
Any
|
The value to process, which might be an I18nString or contain I18nString values |
required |
language
|
str
|
The language code to use for extracting localized strings |
required |
Returns:
Name | Type | Description |
---|---|---|
Any |
Any
|
The processed value with I18nString instances replaced by their language-specific strings |
Examples:
>>> from flask_x_openapi_schema.i18n.i18n_string import I18nStr
>>> i18n_str = I18nStr({"en": "Hello", "fr": "Bonjour"})
>>> process_i18n_value(i18n_str, "en")
'Hello'
>>> process_i18n_value(i18n_str, "fr")
'Bonjour'
>>> process_i18n_value({"greeting": i18n_str}, "en")
{'greeting': 'Hello'}
Source code in src/flask_x_openapi_schema/core/utils.py
pydantic_to_openapi_schema(model)
¶
Convert a Pydantic model to an OpenAPI schema.
Extracts schema information from a Pydantic model and converts it to a format compatible with OpenAPI specifications. The function handles property types, required fields, and includes the model's docstring as the schema description.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
type[BaseModel]
|
The Pydantic model class to convert to an OpenAPI schema |
required |
Returns:
Name | Type | Description |
---|---|---|
dict |
dict[str, Any]
|
The OpenAPI schema representation of the model |
Examples:
>>> from pydantic import BaseModel, Field
>>> class User(BaseModel):
... '''A user model.'''
...
... name: str = Field(..., description="The user's name")
... age: int = Field(..., description="The user's age")
>>> schema = pydantic_to_openapi_schema(User)
>>> schema["type"]
'object'
>>> "name" in schema["properties"]
True
>>> "age" in schema["properties"]
True
>>> schema["description"]
'A user model.'
Source code in src/flask_x_openapi_schema/core/utils.py
python_type_to_openapi_type(python_type)
¶
Convert a Python type to an OpenAPI type.
Maps Python types to their corresponding OpenAPI type definitions. Handles basic types, container types (lists, dicts), and special types like UUID and datetime. Also supports Union types and Pydantic models.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
python_type
|
Any
|
The Python type to convert to an OpenAPI type |
required |
Returns:
Name | Type | Description |
---|---|---|
dict |
dict[str, Any]
|
The OpenAPI type definition for the given Python type |
Examples:
>>> python_type_to_openapi_type(str)
{'type': 'string'}
>>> python_type_to_openapi_type(int)
{'type': 'integer'}
>>> python_type_to_openapi_type(list[str])["type"]
'array'
Source code in src/flask_x_openapi_schema/core/utils.py
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 |
|
response_schema(model, description, status_code=200)
¶
Generate an OpenAPI response schema for a Pydantic model.
Creates an OpenAPI response object that references a Pydantic model schema. The response includes a description and specifies that the content type is application/json.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
type[BaseModel]
|
The Pydantic model to use for the response schema |
required |
description
|
str
|
Description of the response |
required |
status_code
|
int | str
|
HTTP status code for the response (default: 200) |
200
|
Returns:
Name | Type | Description |
---|---|---|
dict |
dict[str, Any]
|
An OpenAPI response schema object |
Examples:
>>> from pydantic import BaseModel
>>> class User(BaseModel):
... name: str
... age: int
>>> schema = response_schema(User, "A user object", 200)
>>> schema["200"]["description"]
'A user object'
>>> schema["200"]["content"]["application/json"]["schema"]["$ref"]
'#/components/schemas/User'
Source code in src/flask_x_openapi_schema/core/utils.py
responses_schema(success_responses, errors=None)
¶
Generate a complete OpenAPI responses schema with success and error responses.
Creates a comprehensive OpenAPI responses object that includes both success responses (with schemas) and error responses. This is useful for documenting all possible responses from an API endpoint.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
success_responses
|
dict[int | str, tuple[type[BaseModel], str]]
|
Dictionary mapping status codes to (model, description) tuples for success responses |
required |
errors
|
dict[int | str, str] | None
|
Optional dictionary mapping status codes to descriptions for error responses |
None
|
Returns:
Name | Type | Description |
---|---|---|
dict |
dict[str, Any]
|
A complete OpenAPI responses schema object |
Examples:
>>> from pydantic import BaseModel
>>> class User(BaseModel):
... name: str
>>> class Error(BaseModel):
... message: str
>>> success = {200: success_response(User, "Success")}
>>> errors = {400: "Bad Request", 404: "Not Found"}
>>> schema = responses_schema(success, errors)
>>> "200" in schema and "400" in schema and "404" in schema
True
Source code in src/flask_x_openapi_schema/core/utils.py
success_response(model, description)
¶
Create a success response tuple for use with responses_schema.
Helper function that creates a tuple containing a model and description, which can be used with the responses_schema function to generate complete OpenAPI response schemas.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
type[BaseModel]
|
The Pydantic model to use for the response schema |
required |
description
|
str
|
Description of the response |
required |
Returns:
Name | Type | Description |
---|---|---|
tuple |
tuple[type[BaseModel], str]
|
A tuple of (model, description) for use with responses_schema |
Examples:
>>> from pydantic import BaseModel
>>> class User(BaseModel):
... name: str
>>> response = success_response(User, "A user object")
>>> response[0] == User
True
>>> response[1]
'A user object'