Flask-RESTful Integration¶
This section provides documentation for the Flask-RESTful specific components of Flask-X-OpenAPI-Schema.
Flask-RESTful Module¶
Flask-RESTful specific implementations for OpenAPI schema generation.
OpenAPIBlueprintMixin
¶
A mixin class for Flask Blueprint to collect OpenAPI metadata from MethodView classes.
This mixin extends Flask's Blueprint class to add OpenAPI schema generation capabilities for MethodView classes. It tracks MethodView classes registered to the blueprint and provides methods to generate OpenAPI schemas.
Examples:
>>> from flask import Blueprint, Flask
>>> from flask.views import MethodView
>>> from flask_x_openapi_schema.x.flask_restful import OpenAPIBlueprintMixin
>>> from flask_x_openapi_schema.x.flask import openapi_metadata, OpenAPIMethodViewMixin
>>>
>>> app = Flask(__name__)
>>>
>>> class OpenAPIBlueprint(OpenAPIBlueprintMixin, Blueprint):
... pass
>>>
>>> bp = OpenAPIBlueprint("api", __name__, url_prefix="/api")
>>>
>>> class ItemView(OpenAPIMethodViewMixin, MethodView):
... @openapi_metadata(summary="Get an item")
... def get(self, item_id):
... return {"id": item_id, "name": "Example Item"}
>>>
>>> # Register the view to the blueprint (returns a view function)
>>> view_func = ItemView.register_to_blueprint(bp, "/items/<item_id>")
>>>
>>> app.register_blueprint(bp)
>>>
>>> # Generate OpenAPI schema
>>> schema = bp.generate_openapi_schema(title="My API", version="1.0.0", description="API for managing items")
Source code in src/flask_x_openapi_schema/x/flask_restful/resources.py
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 |
|
__init__(*args, **kwargs)
¶
Initialize the mixin.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*args
|
Any
|
Arguments to pass to the parent class. |
()
|
**kwargs
|
Any
|
Keyword arguments to pass to the parent class. |
{}
|
Source code in src/flask_x_openapi_schema/x/flask_restful/resources.py
configure_openapi(*, prefix_config=None, **kwargs)
¶
Configure OpenAPI settings for this Blueprint instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prefix_config
|
ConventionalPrefixConfig
|
Configuration object with parameter prefixes |
None
|
**kwargs
|
Any
|
For backward compatibility - will be used to create a config object if prefix_config is None |
{}
|
Source code in src/flask_x_openapi_schema/x/flask_restful/resources.py
generate_openapi_schema(title, version, description='', output_format='yaml', language=None)
¶
Generate an OpenAPI schema for the API.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
title
|
str | I18nStr
|
The title of the API (can be an I18nString). |
required |
version
|
str
|
The version of the API. |
required |
description
|
str | I18nStr
|
The description of the API (can be an I18nString). |
''
|
output_format
|
Literal['json', 'yaml']
|
The output format (json or yaml). |
'yaml'
|
language
|
str | None
|
The language to use for internationalized strings (default: current language). |
None
|
Returns:
Type | Description |
---|---|
Any
|
The OpenAPI schema as a dictionary (if json) or string (if yaml). |
Source code in src/flask_x_openapi_schema/x/flask_restful/resources.py
OpenAPIIntegrationMixin
¶
Bases: Api
A mixin class for the flask-restful Api to collect OpenAPI metadata.
This mixin extends Flask-RESTful's Api class to add OpenAPI schema generation capabilities. It tracks resources added to the API and provides methods to generate OpenAPI schemas.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*args
|
Any
|
Arguments to pass to the parent class. |
()
|
**kwargs
|
Any
|
Keyword arguments to pass to the parent class. |
{}
|
Examples:
>>> from flask import Flask
>>> from flask_restful import Resource
>>> from flask_x_openapi_schema.x.flask_restful import OpenAPIIntegrationMixin, openapi_metadata
>>> from pydantic import BaseModel, Field
>>>
>>> app = Flask(__name__)
>>>
>>> class OpenAPIApi(OpenAPIIntegrationMixin):
... pass
>>>
>>> api = OpenAPIApi(app)
>>>
>>> class ItemResource(Resource):
... @openapi_metadata(summary="Get an item")
... def get(self, item_id):
... return {"id": item_id, "name": "Example Item"}
>>>
>>> api.add_resource(ItemResource, "/items/<item_id>")
>>>
>>> # Generate OpenAPI schema
>>> schema = api.generate_openapi_schema(title="My API", version="1.0.0", description="API for managing items")
Source code in src/flask_x_openapi_schema/x/flask_restful/resources.py
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 |
|
__init__(*args, **kwargs)
¶
Initialize the mixin.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*args
|
Any
|
Arguments to pass to the parent class. |
()
|
**kwargs
|
Any
|
Keyword arguments to pass to the parent class. |
{}
|
Source code in src/flask_x_openapi_schema/x/flask_restful/resources.py
add_resource(resource, *urls, **kwargs)
¶
Add a resource to the API and register it for OpenAPI schema generation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
resource
|
Any
|
The resource class. |
required |
*urls
|
str
|
The URLs to register the resource with. |
()
|
**kwargs
|
Any
|
Additional arguments to pass to the parent method. |
{}
|
Returns:
Type | Description |
---|---|
Any
|
The result of the parent method. |
Source code in src/flask_x_openapi_schema/x/flask_restful/resources.py
configure_openapi(*, prefix_config=None, **kwargs)
¶
Configure OpenAPI settings for this API instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prefix_config
|
ConventionalPrefixConfig
|
Configuration object with parameter prefixes |
None
|
**kwargs
|
Any
|
For backward compatibility - will be used to create a config object if prefix_config is None |
{}
|
Source code in src/flask_x_openapi_schema/x/flask_restful/resources.py
generate_openapi_schema(title, version, description='', output_format='yaml', language=None)
¶
Generate an OpenAPI schema for the API.
This method generates an OpenAPI schema for all resources registered with the API. It supports internationalization through I18nStr objects and can output the schema in either JSON or YAML format.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
title
|
str | I18nStr
|
The title of the API (can be an I18nString). |
required |
version
|
str
|
The version of the API. |
required |
description
|
str | I18nStr
|
The description of the API (can be an I18nString). |
''
|
output_format
|
Literal['json', 'yaml']
|
The output format (json or yaml). |
'yaml'
|
language
|
str | None
|
The language to use for internationalized strings (default: current language). |
None
|
Returns:
Type | Description |
---|---|
Any
|
The OpenAPI schema as a dictionary (if json) or string (if yaml). |
Examples:
>>> from flask import Flask
>>> from flask_restful import Resource
>>> from flask_x_openapi_schema.x.flask_restful import OpenAPIIntegrationMixin, openapi_metadata
>>> app = Flask(__name__)
>>> class OpenAPIApi(OpenAPIIntegrationMixin):
... pass
>>> api = OpenAPIApi(app)
>>> yaml_schema = api.generate_openapi_schema(
... title="My API", version="1.0.0", description="API for managing items"
... )
>>>
>>> json_schema = api.generate_openapi_schema(
... title="My API", version="1.0.0", description="API for managing items", output_format="json"
... )
>>>
>>> from flask_x_openapi_schema import I18nStr
>>> i18n_schema = api.generate_openapi_schema(
... title=I18nStr({"en-US": "My API", "zh-Hans": "我的API"}),
... version="1.0.0",
... description=I18nStr({"en-US": "API for managing items", "zh-Hans": "用于管理项目的API"}),
... language="zh-Hans",
... )
Source code in src/flask_x_openapi_schema/x/flask_restful/resources.py
openapi_metadata(*, summary=None, description=None, tags=None, operation_id=None, deprecated=False, responses=None, 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)
¶
Decorator to add OpenAPI metadata to a Flask-RESTful Resource endpoint.
This decorator adds OpenAPI metadata to a Flask-RESTful Resource endpoint and handles parameter binding for request data. It automatically binds request body, query parameters, path parameters, and file uploads to function parameters based on their type annotations and parameter name prefixes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
summary
|
str | I18nStr | None
|
A short summary of what the operation does. |
None
|
description
|
str | I18nStr | None
|
A verbose explanation of the operation behavior. |
None
|
tags
|
list[str] | None
|
A list of tags for API documentation control. |
None
|
operation_id
|
str | None
|
Unique string used to identify the operation. |
None
|
deprecated
|
bool
|
Declares this operation to be deprecated. |
False
|
responses
|
OpenAPIMetaResponse | None
|
The responses the API can return. |
None
|
security
|
list[dict[str, list[str]]] | None
|
A declaration of which security mechanisms can be used for this operation. |
None
|
external_docs
|
dict[str, str] | None
|
Additional external documentation. |
None
|
language
|
str | None
|
Language code to use for I18nString values (default: current language). |
None
|
prefix_config
|
ConventionalPrefixConfig | None
|
Configuration object 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
|
Returns:
Type | Description |
---|---|
Callable[[F], F] | F
|
The decorated function with OpenAPI metadata attached. |
Examples:
>>> from flask_restful import Resource
>>> from flask_x_openapi_schema.x.flask_restful import openapi_metadata
>>> from flask_x_openapi_schema import OpenAPIMetaResponse, OpenAPIMetaResponseItem
>>> from pydantic import BaseModel, Field
>>>
>>> class ItemRequest(BaseModel):
... name: str = Field(..., description="Item name")
... price: float = Field(..., description="Item price")
>>>
>>> class ItemResponse(BaseModel):
... id: str = Field(..., description="Item ID")
... name: str = Field(..., description="Item name")
... price: float = Field(..., description="Item price")
>>>
>>> class ItemResource(Resource):
... @openapi_metadata(
... summary="Create a new item",
... description="Create a new item with the provided information",
... tags=["items"],
... operation_id="createItem",
... responses=OpenAPIMetaResponse(
... responses={
... "201": OpenAPIMetaResponseItem(model=ItemResponse, description="Item created successfully"),
... "400": OpenAPIMetaResponseItem(description="Invalid request data"),
... }
... ),
... )
... def post(self, _x_body: ItemRequest):
... item = {"id": "123", "name": _x_body.name, "price": _x_body.price}
... return item, 201
Source code in src/flask_x_openapi_schema/x/flask_restful/decorators.py
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 |
|
Decorators¶
Decorators for adding OpenAPI metadata to Flask-RESTful Resource endpoints.
This module provides decorators and utilities for adding OpenAPI metadata to Flask-RESTful Resource class methods. It enables automatic parameter binding, request validation, and OpenAPI schema generation for Flask-RESTful APIs.
The main decorator openapi_metadata
can be applied to Resource methods to add OpenAPI
metadata and enable automatic parameter binding based on type annotations.
Examples:
Basic usage with Flask-RESTful Resource:
>>> from flask_restful import Resource
>>> from flask_x_openapi_schema.x.flask_restful import openapi_metadata
>>> from pydantic import BaseModel, Field
>>>
>>> class UserModel(BaseModel):
... name: str = Field(..., description="User name")
... age: int = Field(..., description="User age")
>>>
>>> class UserResource(Resource):
... @openapi_metadata(summary="Create user", tags=["users"])
... def post(self, _x_body: UserModel):
... return {"name": _x_body.name, "age": _x_body.age}, 201
FlaskRestfulOpenAPIDecorator
¶
Bases: DecoratorBase
OpenAPI metadata decorator for Flask-RESTful Resource.
This class implements the decorator functionality for adding OpenAPI metadata to Flask-RESTful Resource methods. It handles parameter binding, request processing, and OpenAPI schema generation.
Attributes:
Name | Type | Description |
---|---|---|
summary |
str | I18nStr | None
|
A short summary of what the operation does. |
description |
str | I18nStr | None
|
A verbose explanation of the operation behavior. |
tags |
list[str] | None
|
A list of tags for API documentation control. |
operation_id |
str | None
|
Unique string used to identify the operation. |
responses |
OpenAPIMetaResponse | None
|
The responses the API can return. |
deprecated |
bool
|
Declares this operation to be deprecated. |
security |
list[dict[str, list[str]]] | None
|
Security mechanisms for this operation. |
external_docs |
dict[str, str] | None
|
Additional external documentation. |
language |
str | None
|
Language code to use for I18nString values. |
prefix_config |
ConventionalPrefixConfig | None
|
Configuration for parameter prefixes. |
framework |
str
|
The framework being used ('flask_restful'). |
base_decorator |
OpenAPIDecoratorBase | None
|
The base decorator instance. |
parsed_args |
Any | None
|
Parsed arguments from request parser. |
Source code in src/flask_x_openapi_schema/x/flask_restful/decorators.py
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 570 571 572 573 574 575 576 |
|
__call__(func)
¶
Apply the decorator to the function.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
func
|
Callable[..., Any]
|
The function to decorate. |
required |
Returns:
Type | Description |
---|---|
Callable[..., Any]
|
The decorated function. |
Source code in src/flask_x_openapi_schema/x/flask_restful/decorators.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
|
A short summary of what the operation does. |
None
|
description
|
str | I18nStr | None
|
A verbose explanation of the operation behavior. |
None
|
tags
|
list[str] | None
|
A list of tags for API documentation control. |
None
|
operation_id
|
str | None
|
Unique string used to identify the operation. |
None
|
responses
|
OpenAPIMetaResponse | None
|
The responses the API can return. |
None
|
deprecated
|
bool
|
Declares this operation to be deprecated. |
False
|
security
|
list[dict[str, list[str]]] | None
|
A declaration of which security mechanisms can be used for this operation. |
None
|
external_docs
|
dict[str, str] | None
|
Additional external documentation. |
None
|
language
|
str | None
|
Language code to use for I18nString values. |
None
|
prefix_config
|
ConventionalPrefixConfig | None
|
Configuration object 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/x/flask_restful/decorators.py
extract_parameters_from_models(query_model, path_params)
¶
Extract OpenAPI parameters from models.
Converts Pydantic models and path parameters into OpenAPI parameter objects.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
query_model
|
type[BaseModel] | None
|
Pydantic model for query parameters. |
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/x/flask_restful/decorators.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/x/flask_restful/decorators.py
process_query_params(param_name, model, kwargs)
¶
Process query parameters for Flask-RESTful.
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/x/flask_restful/decorators.py
process_request_body(param_name, model, kwargs)
¶
Process request body parameters for Flask-RESTful.
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/x/flask_restful/decorators.py
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 |
|
openapi_metadata(*, summary=None, description=None, tags=None, operation_id=None, deprecated=False, responses=None, 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)
¶
Decorator to add OpenAPI metadata to a Flask-RESTful Resource endpoint.
This decorator adds OpenAPI metadata to a Flask-RESTful Resource endpoint and handles parameter binding for request data. It automatically binds request body, query parameters, path parameters, and file uploads to function parameters based on their type annotations and parameter name prefixes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
summary
|
str | I18nStr | None
|
A short summary of what the operation does. |
None
|
description
|
str | I18nStr | None
|
A verbose explanation of the operation behavior. |
None
|
tags
|
list[str] | None
|
A list of tags for API documentation control. |
None
|
operation_id
|
str | None
|
Unique string used to identify the operation. |
None
|
deprecated
|
bool
|
Declares this operation to be deprecated. |
False
|
responses
|
OpenAPIMetaResponse | None
|
The responses the API can return. |
None
|
security
|
list[dict[str, list[str]]] | None
|
A declaration of which security mechanisms can be used for this operation. |
None
|
external_docs
|
dict[str, str] | None
|
Additional external documentation. |
None
|
language
|
str | None
|
Language code to use for I18nString values (default: current language). |
None
|
prefix_config
|
ConventionalPrefixConfig | None
|
Configuration object 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
|
Returns:
Type | Description |
---|---|
Callable[[F], F] | F
|
The decorated function with OpenAPI metadata attached. |
Examples:
>>> from flask_restful import Resource
>>> from flask_x_openapi_schema.x.flask_restful import openapi_metadata
>>> from flask_x_openapi_schema import OpenAPIMetaResponse, OpenAPIMetaResponseItem
>>> from pydantic import BaseModel, Field
>>>
>>> class ItemRequest(BaseModel):
... name: str = Field(..., description="Item name")
... price: float = Field(..., description="Item price")
>>>
>>> class ItemResponse(BaseModel):
... id: str = Field(..., description="Item ID")
... name: str = Field(..., description="Item name")
... price: float = Field(..., description="Item price")
>>>
>>> class ItemResource(Resource):
... @openapi_metadata(
... summary="Create a new item",
... description="Create a new item with the provided information",
... tags=["items"],
... operation_id="createItem",
... responses=OpenAPIMetaResponse(
... responses={
... "201": OpenAPIMetaResponseItem(model=ItemResponse, description="Item created successfully"),
... "400": OpenAPIMetaResponseItem(description="Invalid request data"),
... }
... ),
... )
... def post(self, _x_body: ItemRequest):
... item = {"id": "123", "name": _x_body.name, "price": _x_body.price}
... return item, 201
Source code in src/flask_x_openapi_schema/x/flask_restful/decorators.py
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 |
|
Resources¶
Extension for the Flask-RESTful Api class to collect OpenAPI metadata.
This module provides mixins and utilities to integrate Flask-RESTful with OpenAPI schema generation. It extends Flask-RESTful's Api class to add OpenAPI schema generation capabilities, tracking resources added to the API and providing methods to generate OpenAPI schemas.
Examples:
Basic usage with Flask-RESTful:
>>> from flask import Flask
>>> from flask_restful import Resource
>>> from flask_x_openapi_schema.x.flask_restful import OpenAPIIntegrationMixin, openapi_metadata
>>> from pydantic import BaseModel, Field
>>>
>>> app = Flask(__name__)
>>>
>>> class OpenAPIApi(OpenAPIIntegrationMixin):
... pass
>>>
>>> api = OpenAPIApi(app)
>>>
>>> class ItemResource(Resource):
... @openapi_metadata(summary="Get an item")
... def get(self, item_id):
... return {"id": item_id, "name": "Example Item"}
>>>
>>> api.add_resource(ItemResource, "/items/<item_id>")
>>>
>>> # Route to serve the OpenAPI schema
>>> schema = api.generate_openapi_schema(title="My API", version="1.0.0", description="API for managing items")
OpenAPIBlueprintMixin
¶
A mixin class for Flask Blueprint to collect OpenAPI metadata from MethodView classes.
This mixin extends Flask's Blueprint class to add OpenAPI schema generation capabilities for MethodView classes. It tracks MethodView classes registered to the blueprint and provides methods to generate OpenAPI schemas.
Examples:
>>> from flask import Blueprint, Flask
>>> from flask.views import MethodView
>>> from flask_x_openapi_schema.x.flask_restful import OpenAPIBlueprintMixin
>>> from flask_x_openapi_schema.x.flask import openapi_metadata, OpenAPIMethodViewMixin
>>>
>>> app = Flask(__name__)
>>>
>>> class OpenAPIBlueprint(OpenAPIBlueprintMixin, Blueprint):
... pass
>>>
>>> bp = OpenAPIBlueprint("api", __name__, url_prefix="/api")
>>>
>>> class ItemView(OpenAPIMethodViewMixin, MethodView):
... @openapi_metadata(summary="Get an item")
... def get(self, item_id):
... return {"id": item_id, "name": "Example Item"}
>>>
>>> # Register the view to the blueprint (returns a view function)
>>> view_func = ItemView.register_to_blueprint(bp, "/items/<item_id>")
>>>
>>> app.register_blueprint(bp)
>>>
>>> # Generate OpenAPI schema
>>> schema = bp.generate_openapi_schema(title="My API", version="1.0.0", description="API for managing items")
Source code in src/flask_x_openapi_schema/x/flask_restful/resources.py
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 |
|
__init__(*args, **kwargs)
¶
Initialize the mixin.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*args
|
Any
|
Arguments to pass to the parent class. |
()
|
**kwargs
|
Any
|
Keyword arguments to pass to the parent class. |
{}
|
Source code in src/flask_x_openapi_schema/x/flask_restful/resources.py
configure_openapi(*, prefix_config=None, **kwargs)
¶
Configure OpenAPI settings for this Blueprint instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prefix_config
|
ConventionalPrefixConfig
|
Configuration object with parameter prefixes |
None
|
**kwargs
|
Any
|
For backward compatibility - will be used to create a config object if prefix_config is None |
{}
|
Source code in src/flask_x_openapi_schema/x/flask_restful/resources.py
generate_openapi_schema(title, version, description='', output_format='yaml', language=None)
¶
Generate an OpenAPI schema for the API.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
title
|
str | I18nStr
|
The title of the API (can be an I18nString). |
required |
version
|
str
|
The version of the API. |
required |
description
|
str | I18nStr
|
The description of the API (can be an I18nString). |
''
|
output_format
|
Literal['json', 'yaml']
|
The output format (json or yaml). |
'yaml'
|
language
|
str | None
|
The language to use for internationalized strings (default: current language). |
None
|
Returns:
Type | Description |
---|---|
Any
|
The OpenAPI schema as a dictionary (if json) or string (if yaml). |
Source code in src/flask_x_openapi_schema/x/flask_restful/resources.py
OpenAPIIntegrationMixin
¶
Bases: Api
A mixin class for the flask-restful Api to collect OpenAPI metadata.
This mixin extends Flask-RESTful's Api class to add OpenAPI schema generation capabilities. It tracks resources added to the API and provides methods to generate OpenAPI schemas.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*args
|
Any
|
Arguments to pass to the parent class. |
()
|
**kwargs
|
Any
|
Keyword arguments to pass to the parent class. |
{}
|
Examples:
>>> from flask import Flask
>>> from flask_restful import Resource
>>> from flask_x_openapi_schema.x.flask_restful import OpenAPIIntegrationMixin, openapi_metadata
>>> from pydantic import BaseModel, Field
>>>
>>> app = Flask(__name__)
>>>
>>> class OpenAPIApi(OpenAPIIntegrationMixin):
... pass
>>>
>>> api = OpenAPIApi(app)
>>>
>>> class ItemResource(Resource):
... @openapi_metadata(summary="Get an item")
... def get(self, item_id):
... return {"id": item_id, "name": "Example Item"}
>>>
>>> api.add_resource(ItemResource, "/items/<item_id>")
>>>
>>> # Generate OpenAPI schema
>>> schema = api.generate_openapi_schema(title="My API", version="1.0.0", description="API for managing items")
Source code in src/flask_x_openapi_schema/x/flask_restful/resources.py
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 |
|
__init__(*args, **kwargs)
¶
Initialize the mixin.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*args
|
Any
|
Arguments to pass to the parent class. |
()
|
**kwargs
|
Any
|
Keyword arguments to pass to the parent class. |
{}
|
Source code in src/flask_x_openapi_schema/x/flask_restful/resources.py
add_resource(resource, *urls, **kwargs)
¶
Add a resource to the API and register it for OpenAPI schema generation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
resource
|
Any
|
The resource class. |
required |
*urls
|
str
|
The URLs to register the resource with. |
()
|
**kwargs
|
Any
|
Additional arguments to pass to the parent method. |
{}
|
Returns:
Type | Description |
---|---|
Any
|
The result of the parent method. |
Source code in src/flask_x_openapi_schema/x/flask_restful/resources.py
configure_openapi(*, prefix_config=None, **kwargs)
¶
Configure OpenAPI settings for this API instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prefix_config
|
ConventionalPrefixConfig
|
Configuration object with parameter prefixes |
None
|
**kwargs
|
Any
|
For backward compatibility - will be used to create a config object if prefix_config is None |
{}
|
Source code in src/flask_x_openapi_schema/x/flask_restful/resources.py
generate_openapi_schema(title, version, description='', output_format='yaml', language=None)
¶
Generate an OpenAPI schema for the API.
This method generates an OpenAPI schema for all resources registered with the API. It supports internationalization through I18nStr objects and can output the schema in either JSON or YAML format.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
title
|
str | I18nStr
|
The title of the API (can be an I18nString). |
required |
version
|
str
|
The version of the API. |
required |
description
|
str | I18nStr
|
The description of the API (can be an I18nString). |
''
|
output_format
|
Literal['json', 'yaml']
|
The output format (json or yaml). |
'yaml'
|
language
|
str | None
|
The language to use for internationalized strings (default: current language). |
None
|
Returns:
Type | Description |
---|---|
Any
|
The OpenAPI schema as a dictionary (if json) or string (if yaml). |
Examples:
>>> from flask import Flask
>>> from flask_restful import Resource
>>> from flask_x_openapi_schema.x.flask_restful import OpenAPIIntegrationMixin, openapi_metadata
>>> app = Flask(__name__)
>>> class OpenAPIApi(OpenAPIIntegrationMixin):
... pass
>>> api = OpenAPIApi(app)
>>> yaml_schema = api.generate_openapi_schema(
... title="My API", version="1.0.0", description="API for managing items"
... )
>>>
>>> json_schema = api.generate_openapi_schema(
... title="My API", version="1.0.0", description="API for managing items", output_format="json"
... )
>>>
>>> from flask_x_openapi_schema import I18nStr
>>> i18n_schema = api.generate_openapi_schema(
... title=I18nStr({"en-US": "My API", "zh-Hans": "我的API"}),
... version="1.0.0",
... description=I18nStr({"en-US": "API for managing items", "zh-Hans": "用于管理项目的API"}),
... language="zh-Hans",
... )
Source code in src/flask_x_openapi_schema/x/flask_restful/resources.py
Utilities¶
Utilities for Flask-RESTful integration.
This module provides utilities for integrating Pydantic models with Flask-RESTful, enabling automatic conversion of Pydantic models to Flask-RESTful RequestParser objects.
The main functionality allows for seamless integration between Pydantic's validation capabilities and Flask-RESTful's request parsing system.
create_reqparse_from_pydantic(model, location='json', bundle_errors=True)
¶
Create a Flask-RESTful RequestParser from a Pydantic model.
Converts a Pydantic model into a Flask-RESTful RequestParser, mapping Pydantic field types to appropriate Python types for request parsing. Handles basic types as well as lists (arrays) and preserves field descriptions and required status.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
type[BaseModel]
|
The Pydantic model class to convert to a RequestParser. |
required |
location
|
str
|
The location to look for arguments. Options include 'json', 'form', 'args', 'headers', etc. Defaults to 'json'. |
'json'
|
bundle_errors
|
bool
|
Whether to bundle all errors in a single response. When False, the first error is returned. Defaults to True. |
True
|
Returns:
Type | Description |
---|---|
RequestParser
|
reqparse.RequestParser: A configured Flask-RESTful RequestParser instance that can be used to parse and validate incoming requests. |
Examples:
>>> from pydantic import BaseModel, Field
>>> from flask_restful import reqparse
>>> class UserModel(BaseModel):
... name: str = Field(..., description="User's full name")
... age: int = Field(..., description="User's age in years")
... tags: list[str] = Field([], description="User tags")
>>> parser = create_reqparse_from_pydantic(UserModel)
>>> isinstance(parser, reqparse.RequestParser)
True