@route_patchclassAPIBlueprint(APIScaffold,Blueprint):"""Flask's `Blueprint` object with some web API support. Examples: ```python from apiflask import APIBlueprint bp = APIBlueprint('foo', __name__) ``` *Version changed: 0.5.0* - Add `enable_openapi` parameter. *Version added: 0.2.0* """def__init__(self,name:str,import_name:str,tag:str|dict|None=None,enable_openapi:bool=True,static_folder:str|None=None,static_url_path:str|None=None,template_folder:str|None=None,url_prefix:str|None=None,subdomain:str|None=None,url_defaults:dict|None=None,root_path:str|None=None,cli_group:str|None=_sentinel,# type: ignore)->None:"""Make a blueprint instance. Arguments: name: The name of the blueprint. Will be prepended to each endpoint name. import_name: The name of the blueprint package, usually `__name__`. This helps locate the `root_path` for the blueprint. tag: The tag of this blueprint. If not set, the `<blueprint name>.title()` will be used (`'foo'` -> `'Foo'`). Accepts a tag name string or an OpenAPI tag dict. Example: ```python bp = APIBlueprint('foo', __name__, tag='Foo') ``` ```python bp = APIBlueprint('foo', __name__, tag={'name': 'Foo'}) ``` enable_openapi: If `False`, will disable OpenAPI support for the current blueprint. Other keyword arguments are directly passed to `flask.Blueprint`. """super().__init__(name,import_name,static_folder=static_folder,static_url_path=static_url_path,template_folder=template_folder,url_prefix=url_prefix,subdomain=subdomain,url_defaults=url_defaults,root_path=root_path,cli_group=cli_group,)self.tag=tagself.enable_openapi=enable_openapi
The name of the blueprint. Will be prepended to
each endpoint name.
required
import_name
str
The name of the blueprint package, usually
__name__. This helps locate the root_path for the
blueprint.
required
tag
str | dict | None
The tag of this blueprint. If not set, the
<blueprint name>.title() will be used ('foo' -> 'Foo').
Accepts a tag name string or an OpenAPI tag dict.
Example:
def__init__(self,name:str,import_name:str,tag:str|dict|None=None,enable_openapi:bool=True,static_folder:str|None=None,static_url_path:str|None=None,template_folder:str|None=None,url_prefix:str|None=None,subdomain:str|None=None,url_defaults:dict|None=None,root_path:str|None=None,cli_group:str|None=_sentinel,# type: ignore)->None:"""Make a blueprint instance. Arguments: name: The name of the blueprint. Will be prepended to each endpoint name. import_name: The name of the blueprint package, usually `__name__`. This helps locate the `root_path` for the blueprint. tag: The tag of this blueprint. If not set, the `<blueprint name>.title()` will be used (`'foo'` -> `'Foo'`). Accepts a tag name string or an OpenAPI tag dict. Example: ```python bp = APIBlueprint('foo', __name__, tag='Foo') ``` ```python bp = APIBlueprint('foo', __name__, tag={'name': 'Foo'}) ``` enable_openapi: If `False`, will disable OpenAPI support for the current blueprint. Other keyword arguments are directly passed to `flask.Blueprint`. """super().__init__(name,import_name,static_folder=static_folder,static_url_path=static_url_path,template_folder=template_folder,url_prefix=url_prefix,subdomain=subdomain,url_defaults=url_defaults,root_path=root_path,cli_group=cli_group,)self.tag=tagself.enable_openapi=enable_openapi
classAPIScaffold:"""A base class for [`APIFlask`][apiflask.app.APIFlask] and [`APIBlueprint`][apiflask.blueprint.APIBlueprint]. This class contains the route shortcut decorators (i.e. `get`, `post`, etc.) and API-related decorators (i.e. `auth_required`, `input`, `output`, `doc`). *Version added: 1.0* """def_method_route(self,method:str,rule:str,options:t.Any)->t.Callable[[T_route],T_route]:if'methods'inoptions:raiseRuntimeError('Use the "route" decorator to use the "methods" argument.')defdecorator(f):ifisinstance(f,type(MethodView)):raiseRuntimeError('The route shortcuts cannot be used with "MethodView" classes, ''use the "route" decorator instead.')returnself.route(rule,methods=[method],**options)(f)returndecoratordefget(self,rule:str,**options:t.Any)->t.Callable[[T_route],T_route]:"""Shortcut for `app.route()` or `app.route(methods=['GET'])`."""returnself._method_route('GET',rule,options)defpost(self,rule:str,**options:t.Any)->t.Callable[[T_route],T_route]:"""Shortcut for `app.route(methods=['POST'])`."""returnself._method_route('POST',rule,options)defput(self,rule:str,**options:t.Any)->t.Callable[[T_route],T_route]:"""Shortcut for `app.route(methods=['PUT'])`."""returnself._method_route('PUT',rule,options)defpatch(self,rule:str,**options:t.Any)->t.Callable[[T_route],T_route]:"""Shortcut for `app.route(methods=['PATCH'])`."""returnself._method_route('PATCH',rule,options)defdelete(self,rule:str,**options:t.Any)->t.Callable[[T_route],T_route]:"""Shortcut for `app.route(methods=['DELETE'])`."""returnself._method_route('DELETE',rule,options)defauth_required(self,auth:HTTPAuthType,roles:list|None=None,optional:str|None=None)->t.Callable[[DecoratedType],DecoratedType]:"""Protect a view with provided authentication settings. > Be sure to put it under the routes decorators (i.e., `app.route`, `app.get`, `app.post`, etc.). Examples: ```python from apiflask import APIFlask, HTTPTokenAuth app = APIFlask(__name__) auth = HTTPTokenAuth() @app.get('/') @app.auth_required(auth) def hello(): return 'Hello'! ``` Arguments: auth: The `auth` object, an instance of [`HTTPBasicAuth`][apiflask.security.HTTPBasicAuth] or [`HTTPTokenAuth`][apiflask.security.HTTPTokenAuth] or [`HTTPAPIKeyAuth`][apiflask.security.HTTPAPIKeyAuth]. roles: The selected roles to allow to visit this view, accepts a list of role names. See [Flask-HTTPAuth's documentation][_role]{target:_blank} for more details. [_role]: https://flask-httpauth.readthedocs.io/en/latest/#user-roles optional: Set to `True` to allow the view to execute even the authentication information is not included with the request, in which case the attribute `auth.current_user` will be `None`. *Version changed: 2.0.0* - Remove the deprecated `role` parameter. *Version changed: 1.0.0* - The `role` parameter is deprecated. *Version changed: 0.12.0* - Move to `APIFlask` and `APIBlueprint` classes. *Version changed: 0.4.0* - Add parameter `roles`. """defdecorator(f):f=_ensure_sync(f)_annotate(f,auth=auth,roles=rolesor[])returnauth.login_required(role=roles,optional=optional)(f)returndecoratordefinput(self,schema:SchemaType,location:str='json',arg_name:str|None=None,schema_name:str|None=None,example:t.Any|None=None,examples:dict[str,t.Any]|None=None,validation:bool=True,**kwargs:t.Any,)->t.Callable[[DecoratedType],DecoratedType]:"""Add input settings for view functions. If the validation passed, the data will be injected into the view function as a keyword argument in the form of `dict` and named `{location}_data`. Otherwise, an error response with the detail of the validation result will be returned. > Be sure to put it under the routes decorators (i.e., `app.route`, `app.get`, `app.post`, etc.). Examples: ```python from apiflask import APIFlask app = APIFlask(__name__) @app.get('/') @app.input(PetIn, location='json') def hello(json_data): print(json_data) return 'Hello'! ``` Arguments: schema: The marshmallow schema or Pydantic model of the input data. location: The location of the input data, one of `'json'` (default), `'files'`, `'form'`, `'cookies'`, `'headers'`, `'query'` (same as `'querystring'`). arg_name: The name of the argument passed to the view function, defaults to `{location}_data`. schema_name: The schema name for dict schema, only needed when you pass a marshmallow schema dict (e.g., `{'name': String(required=True)}`) for `json` location. example: The example data in dict for request body, you should use either `example` or `examples`, not both. examples: Multiple examples for request body, you should pass a dict that contains multiple examples. Example: ```python { 'example foo': { # example name 'summary': 'an example of foo', # summary field is optional 'value': {'name': 'foo', 'id': 1} # example value }, 'example bar': { 'summary': 'an example of bar', 'value': {'name': 'bar', 'id': 2} }, } ``` validation: Flag to allow disabling of validation on input. Default to `True`. *Version changed: 2.2.2 - Add parameter `validation` to allow disabling of validation on input. *Version changed: 2.0.0* - Always pass parsed data to view function as a keyword argument. The argument name will be in the form of `{location}_data`. *Version changed: 1.0* - Ensure only one input body location was used. - Add `form_and_files` and `json_or_form` (from webargs) location. - Rewrite `files` to act as `form_and_files`. - Use correct request content type for `form` and `files`. *Version changed: 0.12.0* - Move to APIFlask and APIBlueprint classes. *Version changed: 0.4.0* - Add parameter `examples`. """defdecorator(f):f=_ensure_sync(f)is_body_location=locationinBODY_LOCATIONSifis_body_locationandhasattr(f,'_spec')and'body'inf._spec:raiseRuntimeError('When using the app.input() decorator, you can only declare one request ''body location (one of "json", "form", "files", "form_and_files", ''and "json_or_form").')# Create schema adapter and use the instantiated schema for spec annotation# This ensures the marshmallow plugin receives schema instancesadapter=registry.create_adapter(schema,schema_name=schema_name)annotation_schema=adapter.schemaiflocation=='json':_annotate(f,body=annotation_schema,body_example=example,body_examples=examples,content_type='application/json',)eliflocation=='form':_annotate(f,body=annotation_schema,body_example=example,body_examples=examples,content_type='application/x-www-form-urlencoded',)eliflocationin['files','form_and_files']:_annotate(f,body=annotation_schema,body_example=example,body_examples=examples,content_type='multipart/form-data',)eliflocation=='json_or_form':_annotate(f,body=annotation_schema,body_example=example,body_examples=examples,content_type=['application/x-www-form-urlencoded','application/json'],)else:ifnothasattr(f,'_spec')orf._spec.get('args')isNone:_annotate(f,args=[])iflocationin['path','view_args']:_annotate(f,omit_default_path_parameters=True)# TODO: Support set example for request parametersf._spec['args'].append((annotation_schema,location))arg_name_val=arg_nameorf'{location}_data'# For marshmallow schemas, use the original webargs approach for compatibilityifadapter.schema_type=='marshmallow':from.schema_adapters.marshmallowimportparserifnotvalidation:@wraps(f)defwrapper(*args:t.Any,**kwargs:t.Any):location_data=parser.load_location_data(schema=annotation_schema,req=flask_request,location=location)kwargs[arg_name_val]=location_datareturnf(*args,**kwargs)returnwrapperreturnparser.use_args(annotation_schema,location=location,arg_name=arg_name_val,**kwargs)(f)# For other schema types (Pydantic, etc.), use the adapter systemelse:@wraps(f)defwrapper(*args:t.Any,**kwargs:t.Any):location_data=adapter.validate_input(flask_request,location,**kwargs)kwargs[arg_name_val]=location_datareturnf(*args,**kwargs)returnwrapperreturndecoratordefoutput(self,schema:SchemaType,status_code:int=200,description:str|None=None,schema_name:str|None=None,example:t.Any|None=None,examples:dict[str,t.Any]|None=None,links:dict[str,t.Any]|None=None,content_type:str|None='application/json',headers:SchemaType|None=None,)->t.Callable[[DecoratedType],DecoratedType]:"""Add output settings for view functions. > Be sure to put it under the routes decorators (i.e., `app.route`, `app.get`, `app.post`, etc.). The decorator will format the return value of your view function with provided marshmallow schema. You can return a dict or an object (such as a model class instance of ORMs). APIFlask will handle the formatting and turn your return value into a JSON response. P.S. The output data will not be validated; it's a design choice of marshmallow. marshmallow 4.0 may be support the output validation. Examples: ```python from apiflask import APIFlask app = APIFlask(__name__) @app.get('/') @app.output(PetOut) def hello(): return the_dict_or_object_match_petout_schema ``` Arguments: schema: The marshmallow schema or Pydantic model of the output data. status_code: The status code of the response, defaults to `200`. description: The description of the response. schema_name: The schema name for dict schema, only needed when you pass a schema dict (e.g., `{'name': String()}`). example: The example data in dict for response body, you should use either `example` or `examples`, not both. examples: Multiple examples for response body, you should pass a dict that contains multiple examples. Example: ```python { 'example foo': { # example name 'summary': 'an example of foo', # summary field is optional 'value': {'name': 'foo', 'id': 1} # example value }, 'example bar': { 'summary': 'an example of bar', 'value': {'name': 'bar', 'id': 2} }, } ``` links: The `links` of response. It accepts a dict which maps a link name to a link object. Example: ```python { 'getAddressByUserId': { 'operationId': 'getUserAddress', 'parameters': { 'userId': '$request.path.id' } } } ``` See the [docs](https://apiflask.com/openapi/#response-links) for more details about setting response links. content_type: The content/media type of the response. It defaults to `application/json`. headers: The schemas of the headers. *Version changed: 2.1.0* - Add parameter `headers`. *Version changed: 2.0.0* - Don't change the status code to 204 for EmptySchema. *Version changed: 1.3.0* - Add parameter `content_type`. *Version changed: 0.12.0* - Move to APIFlask and APIBlueprint classes. *Version changed: 0.10.0* - Add `links` parameter. *Version changed: 0.9.0* - Add base response customization support. *Version changed: 0.6.0* - Support decorating async views. *Version changed: 0.5.2* - Return the `Response` object directly. *Version changed: 0.4.0* - Add parameter `examples`. """body_schema_adapter=registry.create_adapter(schema,schema_name=schema_name)body_schema=body_schema_adapter.schemaheaders_schema=NoneifheadersisnotNone:headers_schema_adapter=registry.create_adapter(headers,schema_name=None)headers_schema=headers_schema_adapter.schemadefdecorator(f):f=_ensure_sync(f)_annotate(f,response={'schema':body_schema,'schema_adapter_many':body_schema_adapter.many,# Store the many flag'status_code':status_code,'description':description,'example':example,'examples':examples,'links':links,'content_type':content_type,'headers':headers_schema,},)def_jsonify(obj:t.Any,many:bool=_sentinel,# type: ignore*args:t.Any,**kwargs:t.Any,)->Response:# pragma: no cover"""Serialize output using schema adapters."""ifisinstance(body_schema,FileSchema):returnobj# type: ignore# Handle many parameterifmanyis_sentinel:# Check adapter's many flag first (for list[Model] syntax)# Then check schema's many attribute (for marshmallow compatibility)many=getattr(body_schema_adapter,'many',False)orgetattr(schema,'many',False)# type: ignorebase_schema:OpenAPISchemaType=current_app.config['BASE_RESPONSE_SCHEMA']ifbase_schemaisnotNoneandstatus_code!=204:data_key:str=current_app.config['BASE_RESPONSE_DATA_KEY']ifisinstance(obj,dict):ifdata_keynotinobj:raiseRuntimeError(f'The data key {data_key!r} is not found in the returned dict.')# Serialize the data partobj[data_key]=body_schema_adapter.serialize_output(obj[data_key],many=many)else:ifnothasattr(obj,data_key):raiseRuntimeError(f'The data key {data_key!r} is not found in the returned object.')# Serialize the data partdata_value=getattr(obj,data_key)serialized_data=body_schema_adapter.serialize_output(data_value,many=many)setattr(obj,data_key,serialized_data)base_schema_adapter=registry.create_adapter(base_schema)data=base_schema_adapter.serialize_output(obj)# type: ignoreelse:data=body_schema_adapter.serialize_output(obj,many=many)# type: ignorereturnjsonify(data,*args,**kwargs)@wraps(f)def_response(*args:t.Any,**kwargs:t.Any)->ResponseReturnValueType:rv=f(*args,**kwargs)ifisinstance(rv,Response):returnrvifnotisinstance(rv,tuple):return_jsonify(rv),status_codejson=_jsonify(rv[0])iflen(rv)==2:rv=(json,rv[1])ifisinstance(rv[1],int)else(json,status_code,rv[1])eliflen(rv)>=3:rv=(json,rv[1],rv[2])else:rv=(json,status_code)returnrv# type: ignorereturn_responsereturndecoratordefdoc(self,summary:str|None=None,description:str|None=None,tags:list[str]|None=None,responses:ResponsesType|None=None,deprecated:bool|None=None,hide:bool|None=None,operation_id:str|None=None,security:str|list[str|dict[str,list]]|None=None,extensions:dict[str,t.Any]|None=None,)->t.Callable[[DecoratedType],DecoratedType]:"""Set up the OpenAPI Spec for view functions. > Be sure to put it under the routes decorators (i.e., `app.route`, `app.get`, `app.post`, etc.). Examples: ```python from apiflask import APIFlask app = APIFlask(__name__) @app.get('/') @app.doc(summary='Say hello', tags=['Foo']) def hello(): return 'Hello' ``` Arguments: summary: The summary of this endpoint. If not set, the name of the view function will be used. If your view function is named with `get_pet`, then the summary will be "Get Pet". If the view function has a docstring, then the first line of the docstring will be used. The precedence will be: ``` @app.doc(summary='blah') > the first line of docstring > the view function name ``` description: The description of this endpoint. If not set, the lines after the empty line of the docstring will be used. tags: A list of tag names of this endpoint, map the tags you passed in the `app.tags` attribute. If `app.tags` is not set, the blueprint name will be used as tag name. responses: The other responses for this view function, accepts a list of status codes (`[404, 418]`) or a dict in a format of either `{404: 'Not Found'}` or `{404: {'description': 'Not Found', 'content': {'application/json': {'schema': FooSchema}}}}`. If a dict is passed and a response with the same status code is already present, the existing data will be overwritten. deprecated: Flag this endpoint as deprecated in API docs. hide: Hide this endpoint in API docs. operation_id: The `operationId` of this endpoint. Set config `AUTO_OPERATION_ID` to `True` to enable the auto-generating of operationId (in the format of `{method}_{endpoint}`). security: The `security` used for this endpoint. Match the security info specified in the `SECURITY_SCHEMES` configuration. If you don't need specify the scopes, just pass a security name (equals to `[{'foo': []}]`) or a list of security names (equals to `[{'foo': []}, {'bar': []}]`). extensions: The spec extensions of this endpoint (OpenAPI operation object). The fields in this extensions dict should start with "x-" prefix. See more details in the [Specification Extensions](https://spec.openapis.org/oas/v3.1.0#specification-extensions) chapter of OpenAPI docs. *Version changed: 2.2.0* - Add `extensions` parameter to support setting spec extensions. *Version changed: 2.0.0* - Remove the deprecated `tag` parameter. - Expand `responses` to support additional structure and parameters. *Version changed: 1.0* - Add `security` parameter to support customizing security info. - The `role` parameter is deprecated. *Version changed: 0.12.0* - Move to `APIFlask` and `APIBlueprint` classes. *Version changed: 0.10.0* - Add parameter `operation_id`. *Version changed: 0.5.0* - Change the default value of parameters `hide` and `deprecated` from `False` to `None`. *Version changed: 0.4.0* - Add parameter `tag`. *Version changed: 0.3.0* - Change the default value of `deprecated` from `None` to `False`. - Rename parameter `tags` to `tag`. *Version added: 0.2.0* """defdecorator(f):f=_ensure_sync(f)_annotate(f,summary=summary,description=description,tags=tags,responses=responses,deprecated=deprecated,hide=hide,operation_id=operation_id,security=security,extensions=extensions,)returnfreturndecorator
The auth object, an instance of
HTTPBasicAuth
or HTTPTokenAuth
or [HTTPAPIKeyAuth][apiflask.security.HTTPAPIKeyAuth].
required
roles
list | None
The selected roles to allow to visit this view, accepts a list of role names.
See Flask-HTTPAuth's documentation for more details.
None
optional
str | None
Set to True to allow the view to execute even the authentication
information is not included with the request, in which case the attribute
auth.current_user will be None.
defauth_required(self,auth:HTTPAuthType,roles:list|None=None,optional:str|None=None)->t.Callable[[DecoratedType],DecoratedType]:"""Protect a view with provided authentication settings. > Be sure to put it under the routes decorators (i.e., `app.route`, `app.get`, `app.post`, etc.). Examples: ```python from apiflask import APIFlask, HTTPTokenAuth app = APIFlask(__name__) auth = HTTPTokenAuth() @app.get('/') @app.auth_required(auth) def hello(): return 'Hello'! ``` Arguments: auth: The `auth` object, an instance of [`HTTPBasicAuth`][apiflask.security.HTTPBasicAuth] or [`HTTPTokenAuth`][apiflask.security.HTTPTokenAuth] or [`HTTPAPIKeyAuth`][apiflask.security.HTTPAPIKeyAuth]. roles: The selected roles to allow to visit this view, accepts a list of role names. See [Flask-HTTPAuth's documentation][_role]{target:_blank} for more details. [_role]: https://flask-httpauth.readthedocs.io/en/latest/#user-roles optional: Set to `True` to allow the view to execute even the authentication information is not included with the request, in which case the attribute `auth.current_user` will be `None`. *Version changed: 2.0.0* - Remove the deprecated `role` parameter. *Version changed: 1.0.0* - The `role` parameter is deprecated. *Version changed: 0.12.0* - Move to `APIFlask` and `APIBlueprint` classes. *Version changed: 0.4.0* - Add parameter `roles`. """defdecorator(f):f=_ensure_sync(f)_annotate(f,auth=auth,roles=rolesor[])returnauth.login_required(role=roles,optional=optional)(f)returndecorator
defdelete(self,rule:str,**options:t.Any)->t.Callable[[T_route],T_route]:"""Shortcut for `app.route(methods=['DELETE'])`."""returnself._method_route('DELETE',rule,options)
The summary of this endpoint. If not set, the name of the view function
will be used. If your view function is named with get_pet, then the summary
will be "Get Pet". If the view function has a docstring, then the first
line of the docstring will be used. The precedence will be:
@app.doc(summary='blah') > the first line of docstring > the view function name
None
description
str | None
The description of this endpoint. If not set, the lines after the empty
line of the docstring will be used.
None
tags
list[str] | None
A list of tag names of this endpoint, map the tags you passed in the app.tags
attribute. If app.tags is not set, the blueprint name will be used as tag name.
None
responses
ResponsesType | None
The other responses for this view function, accepts a list of status codes
([404, 418]) or a dict in a format of either {404: 'Not Found'} or
{404: {'description': 'Not Found', 'content': {'application/json':
{'schema': FooSchema}}}}. If a dict is passed and a response with the same status
code is already present, the existing data will be overwritten.
None
deprecated
bool | None
Flag this endpoint as deprecated in API docs.
None
hide
bool | None
Hide this endpoint in API docs.
None
operation_id
str | None
The operationId of this endpoint. Set config AUTO_OPERATION_ID to
True to enable the auto-generating of operationId (in the format of
{method}_{endpoint}).
None
security
str | list[str | dict[str, list]] | None
The security used for this endpoint. Match the security info specified in
the SECURITY_SCHEMES configuration. If you don't need specify the scopes, just
pass a security name (equals to [{'foo': []}]) or a list of security names (equals
to [{'foo': []}, {'bar': []}]).
None
extensions
dict[str, Any] | None
The spec extensions of this endpoint (OpenAPI operation object). The fields
in this extensions dict should start with "x-" prefix. See more details in the
Specification Extensions
chapter of OpenAPI docs.
None
Version changed: 2.2.0
Add extensions parameter to support setting spec extensions.
Version changed: 2.0.0
Remove the deprecated tag parameter.
Expand responses to support additional structure and parameters.
Version changed: 1.0
Add security parameter to support customizing security info.
The role parameter is deprecated.
Version changed: 0.12.0
Move to APIFlask and APIBlueprint classes.
Version changed: 0.10.0
Add parameter operation_id.
Version changed: 0.5.0
Change the default value of parameters hide and deprecated from False to None.
Version changed: 0.4.0
Add parameter tag.
Version changed: 0.3.0
Change the default value of deprecated from None to False.
defdoc(self,summary:str|None=None,description:str|None=None,tags:list[str]|None=None,responses:ResponsesType|None=None,deprecated:bool|None=None,hide:bool|None=None,operation_id:str|None=None,security:str|list[str|dict[str,list]]|None=None,extensions:dict[str,t.Any]|None=None,)->t.Callable[[DecoratedType],DecoratedType]:"""Set up the OpenAPI Spec for view functions. > Be sure to put it under the routes decorators (i.e., `app.route`, `app.get`, `app.post`, etc.). Examples: ```python from apiflask import APIFlask app = APIFlask(__name__) @app.get('/') @app.doc(summary='Say hello', tags=['Foo']) def hello(): return 'Hello' ``` Arguments: summary: The summary of this endpoint. If not set, the name of the view function will be used. If your view function is named with `get_pet`, then the summary will be "Get Pet". If the view function has a docstring, then the first line of the docstring will be used. The precedence will be: ``` @app.doc(summary='blah') > the first line of docstring > the view function name ``` description: The description of this endpoint. If not set, the lines after the empty line of the docstring will be used. tags: A list of tag names of this endpoint, map the tags you passed in the `app.tags` attribute. If `app.tags` is not set, the blueprint name will be used as tag name. responses: The other responses for this view function, accepts a list of status codes (`[404, 418]`) or a dict in a format of either `{404: 'Not Found'}` or `{404: {'description': 'Not Found', 'content': {'application/json': {'schema': FooSchema}}}}`. If a dict is passed and a response with the same status code is already present, the existing data will be overwritten. deprecated: Flag this endpoint as deprecated in API docs. hide: Hide this endpoint in API docs. operation_id: The `operationId` of this endpoint. Set config `AUTO_OPERATION_ID` to `True` to enable the auto-generating of operationId (in the format of `{method}_{endpoint}`). security: The `security` used for this endpoint. Match the security info specified in the `SECURITY_SCHEMES` configuration. If you don't need specify the scopes, just pass a security name (equals to `[{'foo': []}]`) or a list of security names (equals to `[{'foo': []}, {'bar': []}]`). extensions: The spec extensions of this endpoint (OpenAPI operation object). The fields in this extensions dict should start with "x-" prefix. See more details in the [Specification Extensions](https://spec.openapis.org/oas/v3.1.0#specification-extensions) chapter of OpenAPI docs. *Version changed: 2.2.0* - Add `extensions` parameter to support setting spec extensions. *Version changed: 2.0.0* - Remove the deprecated `tag` parameter. - Expand `responses` to support additional structure and parameters. *Version changed: 1.0* - Add `security` parameter to support customizing security info. - The `role` parameter is deprecated. *Version changed: 0.12.0* - Move to `APIFlask` and `APIBlueprint` classes. *Version changed: 0.10.0* - Add parameter `operation_id`. *Version changed: 0.5.0* - Change the default value of parameters `hide` and `deprecated` from `False` to `None`. *Version changed: 0.4.0* - Add parameter `tag`. *Version changed: 0.3.0* - Change the default value of `deprecated` from `None` to `False`. - Rename parameter `tags` to `tag`. *Version added: 0.2.0* """defdecorator(f):f=_ensure_sync(f)_annotate(f,summary=summary,description=description,tags=tags,responses=responses,deprecated=deprecated,hide=hide,operation_id=operation_id,security=security,extensions=extensions,)returnfreturndecorator
Shortcut for app.route() or app.route(methods=['GET']).
Source code in apiflask/scaffold.py
737475
defget(self,rule:str,**options:t.Any)->t.Callable[[T_route],T_route]:"""Shortcut for `app.route()` or `app.route(methods=['GET'])`."""returnself._method_route('GET',rule,options)
If the validation passed, the data will be injected into the view
function as a keyword argument in the form of dict and named {location}_data.
Otherwise, an error response with the detail of the validation result will be
returned.
Be sure to put it under the routes decorators (i.e., app.route, app.get,
app.post, etc.).
The marshmallow schema or Pydantic model of the input data.
required
location
str
The location of the input data, one of 'json' (default),
'files', 'form', 'cookies', 'headers', 'query'
(same as 'querystring').
'json'
arg_name
str | None
The name of the argument passed to the view function,
defaults to {location}_data.
None
schema_name
str | None
The schema name for dict schema, only needed when you pass
a marshmallow schema dict (e.g., {'name': String(required=True)}) for json
location.
None
example
Any | None
The example data in dict for request body, you should use either
example or examples, not both.
None
examples
dict[str, Any] | None
Multiple examples for request body, you should pass a dict
that contains multiple examples. Example:
{'example foo':{# example name'summary':'an example of foo',# summary field is optional'value':{'name':'foo','id':1}# example value},'example bar':{'summary':'an example of bar','value':{'name':'bar','id':2}},}
None
validation
bool
Flag to allow disabling of validation on input. Default to True.
True
*Version changed: 2.2.2
Add parameter validation to allow disabling of validation on input.
Version changed: 2.0.0
Always pass parsed data to view function as a keyword argument.
The argument name will be in the form of {location}_data.
Version changed: 1.0
Ensure only one input body location was used.
Add form_and_files and json_or_form (from webargs) location.
Rewrite files to act as form_and_files.
Use correct request content type for form and files.
definput(self,schema:SchemaType,location:str='json',arg_name:str|None=None,schema_name:str|None=None,example:t.Any|None=None,examples:dict[str,t.Any]|None=None,validation:bool=True,**kwargs:t.Any,)->t.Callable[[DecoratedType],DecoratedType]:"""Add input settings for view functions. If the validation passed, the data will be injected into the view function as a keyword argument in the form of `dict` and named `{location}_data`. Otherwise, an error response with the detail of the validation result will be returned. > Be sure to put it under the routes decorators (i.e., `app.route`, `app.get`, `app.post`, etc.). Examples: ```python from apiflask import APIFlask app = APIFlask(__name__) @app.get('/') @app.input(PetIn, location='json') def hello(json_data): print(json_data) return 'Hello'! ``` Arguments: schema: The marshmallow schema or Pydantic model of the input data. location: The location of the input data, one of `'json'` (default), `'files'`, `'form'`, `'cookies'`, `'headers'`, `'query'` (same as `'querystring'`). arg_name: The name of the argument passed to the view function, defaults to `{location}_data`. schema_name: The schema name for dict schema, only needed when you pass a marshmallow schema dict (e.g., `{'name': String(required=True)}`) for `json` location. example: The example data in dict for request body, you should use either `example` or `examples`, not both. examples: Multiple examples for request body, you should pass a dict that contains multiple examples. Example: ```python { 'example foo': { # example name 'summary': 'an example of foo', # summary field is optional 'value': {'name': 'foo', 'id': 1} # example value }, 'example bar': { 'summary': 'an example of bar', 'value': {'name': 'bar', 'id': 2} }, } ``` validation: Flag to allow disabling of validation on input. Default to `True`. *Version changed: 2.2.2 - Add parameter `validation` to allow disabling of validation on input. *Version changed: 2.0.0* - Always pass parsed data to view function as a keyword argument. The argument name will be in the form of `{location}_data`. *Version changed: 1.0* - Ensure only one input body location was used. - Add `form_and_files` and `json_or_form` (from webargs) location. - Rewrite `files` to act as `form_and_files`. - Use correct request content type for `form` and `files`. *Version changed: 0.12.0* - Move to APIFlask and APIBlueprint classes. *Version changed: 0.4.0* - Add parameter `examples`. """defdecorator(f):f=_ensure_sync(f)is_body_location=locationinBODY_LOCATIONSifis_body_locationandhasattr(f,'_spec')and'body'inf._spec:raiseRuntimeError('When using the app.input() decorator, you can only declare one request ''body location (one of "json", "form", "files", "form_and_files", ''and "json_or_form").')# Create schema adapter and use the instantiated schema for spec annotation# This ensures the marshmallow plugin receives schema instancesadapter=registry.create_adapter(schema,schema_name=schema_name)annotation_schema=adapter.schemaiflocation=='json':_annotate(f,body=annotation_schema,body_example=example,body_examples=examples,content_type='application/json',)eliflocation=='form':_annotate(f,body=annotation_schema,body_example=example,body_examples=examples,content_type='application/x-www-form-urlencoded',)eliflocationin['files','form_and_files']:_annotate(f,body=annotation_schema,body_example=example,body_examples=examples,content_type='multipart/form-data',)eliflocation=='json_or_form':_annotate(f,body=annotation_schema,body_example=example,body_examples=examples,content_type=['application/x-www-form-urlencoded','application/json'],)else:ifnothasattr(f,'_spec')orf._spec.get('args')isNone:_annotate(f,args=[])iflocationin['path','view_args']:_annotate(f,omit_default_path_parameters=True)# TODO: Support set example for request parametersf._spec['args'].append((annotation_schema,location))arg_name_val=arg_nameorf'{location}_data'# For marshmallow schemas, use the original webargs approach for compatibilityifadapter.schema_type=='marshmallow':from.schema_adapters.marshmallowimportparserifnotvalidation:@wraps(f)defwrapper(*args:t.Any,**kwargs:t.Any):location_data=parser.load_location_data(schema=annotation_schema,req=flask_request,location=location)kwargs[arg_name_val]=location_datareturnf(*args,**kwargs)returnwrapperreturnparser.use_args(annotation_schema,location=location,arg_name=arg_name_val,**kwargs)(f)# For other schema types (Pydantic, etc.), use the adapter systemelse:@wraps(f)defwrapper(*args:t.Any,**kwargs:t.Any):location_data=adapter.validate_input(flask_request,location,**kwargs)kwargs[arg_name_val]=location_datareturnf(*args,**kwargs)returnwrapperreturndecorator
Be sure to put it under the routes decorators (i.e., app.route, app.get,
app.post, etc.).
The decorator will format the return value of your view function with
provided marshmallow schema. You can return a dict or an object (such
as a model class instance of ORMs). APIFlask will handle the formatting
and turn your return value into a JSON response.
P.S. The output data will not be validated; it's a design choice of marshmallow.
marshmallow 4.0 may be support the output validation.
The marshmallow schema or Pydantic model of the output data.
required
status_code
int
The status code of the response, defaults to 200.
200
description
str | None
The description of the response.
None
schema_name
str | None
The schema name for dict schema, only needed when you pass
a schema dict (e.g., {'name': String()}).
None
example
Any | None
The example data in dict for response body, you should use either
example or examples, not both.
None
examples
dict[str, Any] | None
Multiple examples for response body, you should pass a dict
that contains multiple examples. Example:
{'example foo':{# example name'summary':'an example of foo',# summary field is optional'value':{'name':'foo','id':1}# example value},'example bar':{'summary':'an example of bar','value':{'name':'bar','id':2}},}
None
links
dict[str, Any] | None
The links of response. It accepts a dict which maps a link name to
a link object. Example:
defoutput(self,schema:SchemaType,status_code:int=200,description:str|None=None,schema_name:str|None=None,example:t.Any|None=None,examples:dict[str,t.Any]|None=None,links:dict[str,t.Any]|None=None,content_type:str|None='application/json',headers:SchemaType|None=None,)->t.Callable[[DecoratedType],DecoratedType]:"""Add output settings for view functions. > Be sure to put it under the routes decorators (i.e., `app.route`, `app.get`, `app.post`, etc.). The decorator will format the return value of your view function with provided marshmallow schema. You can return a dict or an object (such as a model class instance of ORMs). APIFlask will handle the formatting and turn your return value into a JSON response. P.S. The output data will not be validated; it's a design choice of marshmallow. marshmallow 4.0 may be support the output validation. Examples: ```python from apiflask import APIFlask app = APIFlask(__name__) @app.get('/') @app.output(PetOut) def hello(): return the_dict_or_object_match_petout_schema ``` Arguments: schema: The marshmallow schema or Pydantic model of the output data. status_code: The status code of the response, defaults to `200`. description: The description of the response. schema_name: The schema name for dict schema, only needed when you pass a schema dict (e.g., `{'name': String()}`). example: The example data in dict for response body, you should use either `example` or `examples`, not both. examples: Multiple examples for response body, you should pass a dict that contains multiple examples. Example: ```python { 'example foo': { # example name 'summary': 'an example of foo', # summary field is optional 'value': {'name': 'foo', 'id': 1} # example value }, 'example bar': { 'summary': 'an example of bar', 'value': {'name': 'bar', 'id': 2} }, } ``` links: The `links` of response. It accepts a dict which maps a link name to a link object. Example: ```python { 'getAddressByUserId': { 'operationId': 'getUserAddress', 'parameters': { 'userId': '$request.path.id' } } } ``` See the [docs](https://apiflask.com/openapi/#response-links) for more details about setting response links. content_type: The content/media type of the response. It defaults to `application/json`. headers: The schemas of the headers. *Version changed: 2.1.0* - Add parameter `headers`. *Version changed: 2.0.0* - Don't change the status code to 204 for EmptySchema. *Version changed: 1.3.0* - Add parameter `content_type`. *Version changed: 0.12.0* - Move to APIFlask and APIBlueprint classes. *Version changed: 0.10.0* - Add `links` parameter. *Version changed: 0.9.0* - Add base response customization support. *Version changed: 0.6.0* - Support decorating async views. *Version changed: 0.5.2* - Return the `Response` object directly. *Version changed: 0.4.0* - Add parameter `examples`. """body_schema_adapter=registry.create_adapter(schema,schema_name=schema_name)body_schema=body_schema_adapter.schemaheaders_schema=NoneifheadersisnotNone:headers_schema_adapter=registry.create_adapter(headers,schema_name=None)headers_schema=headers_schema_adapter.schemadefdecorator(f):f=_ensure_sync(f)_annotate(f,response={'schema':body_schema,'schema_adapter_many':body_schema_adapter.many,# Store the many flag'status_code':status_code,'description':description,'example':example,'examples':examples,'links':links,'content_type':content_type,'headers':headers_schema,},)def_jsonify(obj:t.Any,many:bool=_sentinel,# type: ignore*args:t.Any,**kwargs:t.Any,)->Response:# pragma: no cover"""Serialize output using schema adapters."""ifisinstance(body_schema,FileSchema):returnobj# type: ignore# Handle many parameterifmanyis_sentinel:# Check adapter's many flag first (for list[Model] syntax)# Then check schema's many attribute (for marshmallow compatibility)many=getattr(body_schema_adapter,'many',False)orgetattr(schema,'many',False)# type: ignorebase_schema:OpenAPISchemaType=current_app.config['BASE_RESPONSE_SCHEMA']ifbase_schemaisnotNoneandstatus_code!=204:data_key:str=current_app.config['BASE_RESPONSE_DATA_KEY']ifisinstance(obj,dict):ifdata_keynotinobj:raiseRuntimeError(f'The data key {data_key!r} is not found in the returned dict.')# Serialize the data partobj[data_key]=body_schema_adapter.serialize_output(obj[data_key],many=many)else:ifnothasattr(obj,data_key):raiseRuntimeError(f'The data key {data_key!r} is not found in the returned object.')# Serialize the data partdata_value=getattr(obj,data_key)serialized_data=body_schema_adapter.serialize_output(data_value,many=many)setattr(obj,data_key,serialized_data)base_schema_adapter=registry.create_adapter(base_schema)data=base_schema_adapter.serialize_output(obj)# type: ignoreelse:data=body_schema_adapter.serialize_output(obj,many=many)# type: ignorereturnjsonify(data,*args,**kwargs)@wraps(f)def_response(*args:t.Any,**kwargs:t.Any)->ResponseReturnValueType:rv=f(*args,**kwargs)ifisinstance(rv,Response):returnrvifnotisinstance(rv,tuple):return_jsonify(rv),status_codejson=_jsonify(rv[0])iflen(rv)==2:rv=(json,rv[1])ifisinstance(rv[1],int)else(json,status_code,rv[1])eliflen(rv)>=3:rv=(json,rv[1],rv[2])else:rv=(json,status_code)returnrv# type: ignorereturn_responsereturndecorator
defpatch(self,rule:str,**options:t.Any)->t.Callable[[T_route],T_route]:"""Shortcut for `app.route(methods=['PATCH'])`."""returnself._method_route('PATCH',rule,options)
defpost(self,rule:str,**options:t.Any)->t.Callable[[T_route],T_route]:"""Shortcut for `app.route(methods=['POST'])`."""returnself._method_route('POST',rule,options)
defput(self,rule:str,**options:t.Any)->t.Callable[[T_route],T_route]:"""Shortcut for `app.route(methods=['PUT'])`."""returnself._method_route('PUT',rule,options)