基本用法
环境
pip install apiflask
Create an app instance with APIFlask class
from apiflask import APIFlask
app = APIFlask(__name__)
@app.get('/')
def index():
return {'message': 'hello'}
The default title and version of the API will be APIFlask and 0.1.0; you can pass the title and the version arguments to change these settings:
app = APIFlask(__name__, title='Wonderful API', version='1.0')
To run this application, you can save it as app.py, then run the flask run command:
flask run
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
If your script's name isn't app.py, you will need to declare which application should be started before execute flask run. See the note below for more details.
If you want to make the application restart whenever the code changes, you can enable reloader with --reload option:
flask run --reload
开启debug模式
flask --debug run
Move to new API decorators
从APIFlask 0.12开始,四个独立的API装饰器 (i.e. @input, @output, @doc, and @auth_required) 被移动到APIFlask 和 APIBlueprint classes. 现在用您的应用程序或蓝图实例访问它们:
from apiflask import APIFlask
app = APIFlask(__name__)
@app.get('/')
@app.input(Foo)
@app.output(Bar)
def hello():
return {'message': 'Hello'}
代替:
from apiflask import APIFlask, input, output
app = APIFlask(__name__)
@app.get('/')
@input(Foo)
@output(Bar)
def hello():
return {'message': 'Hello'}
使用@app.input验证和反序列化请求数据的输入
要验证和反序列化请求体或请求查询参数,我们需要首先创建一个数据模式类。可以将其视为描述有效传入数据的一种方式。如果您已经熟悉了marshmallow,那么您已经知道如何编写数据模式。
- A schema class should inherit the
apiflask.Schemaclass - fields are represented with field classes in
apiflask.fields - 要用特定规则验证字段,您可以传递一个验证器或一个验证器列表 (import them from
apiflask.validators) 到 field class的validate属性/参数: Here is a simple input schema for a Pet input resource:
from apiflask import Schema
from apiflask.fields import Integer, String
from apiflask.validators import Length, OneOf
class PetIn(Schema):
name = String(required=True, validate=Length(0, 10))
category = String(required=True, validate=OneOf(['dog', 'cat']))
使用此模式,我们声明输入请求正文应以以下格式出现:
{
"name": "the name of the pet",
"category": "the category of the pet: one of dog and cat"
}
现在让我们将它添加到用于创建新宠物的视图函数中:
from apiflask import APIFlask, Schema, input
from apiflask.fields import Integer, String
from apiflask.validators import Length, OneOf
app = APIFlask(__name__)
class PetIn(Schema):
name = String(required=True, validate=Length(0, 10))
category = String(required=True, validate=OneOf(['dog', 'cat']))
@app.post('/pets')
@app.input(PetIn)
def create_pet(data):
print(data)
return {'message': 'created'}, 201
您只需要将模式类传递给 @app.input 装饰器。收到请求后,APIFlask 将根据模式验证请求主体。
如果验证通过,数据将以 dict 的形式作为位置参数注入到视图函数中。否则,将返回包含验证结果详细信息的错误响应。
在上面的示例中,我使用名称数据来接受输入数据字典。您可以将参数名称更改为您喜欢的任何名称。因为这是一个字典,你可以做这样的事情来创建一个 ORM 模型实例:
@app.post('/pets')
@app.input(PetIn)
@app.output(PetOut)
def create_pet(pet_id, data):
pet = Pet(**data)
return pet
或者像这样更新一个 ORM 模型类实例:
@app.patch('/pets/<int:pet_id>')
@app.input(PetIn)
@app.output(PetOut)
def update_pet(pet_id, data):
pet = Pet.query.get(pet_id)
for attr, value in data.items():
setattr(pet, attr, value)
return pet
如果你想用不同的位置标记输入,你可以为 @app.input() 装饰器传递一个位置参数,值可以是:
-
Request JSON body:
'json'(default) -
Upload files:
'files' -
Form data:
'form' -
Form data and files:
'form_and_files' -
Cookies:
'cookies' -
HTTP headers:
'headers' -
Query string:
'query'(same as'querystring') -
Path variable (URL variable):
'path'(same as'view_args', added in APIFlask 1.0.2)
Use @app.output to format response data
类似地,我们可以用@app为输出数据定义一个模式。输出装饰。下面是一个例子:
from apiflask.fields import String, Integer
class PetOut(Schema):
id = Integer()
name = String()
category = String()
现在将它添加到用于获取宠物资源的视图函数中
from apiflask import APIFlask, output
from apiflask.fields import String, Integer
app = APIFlask(__name__)
class PetOut(Schema):
id = Integer()
name = String(dump_default='default name') #使用 dump_default 参数为输出字段设置默认值:
category = String()
@app.get('/pets/<int:pet_id>')
@app.output(PetOut)
def get_pet(pet_id):
return {
'name': 'Coco',
'category': 'dog'
}
输出响应的默认状态代码为 200,您可以使用status_code参数设置不同的状态代码:
@app.post('/pets')
@app.input(PetIn)
@app.output(PetOut, status_code=201)
def create_pet(data):
data['id'] = 2
return data
如果要返回 204 响应,可以使用 apiflask.schemas 中的 EmptySchema:
from apiflask.schemas import EmptySchema
@app.delete('/pets/<int:pet_id>')
@app.output(EmptySchema, status_code=204)
def delete_pet(pet_id):
return ''
#从 0.4.0 版本开始,您可以使用空字典来表示空模式:
@app.delete('/pets/<int:pet_id>')
@app.output({}, status_code=204)
def delete_pet(pet_id):
return ''
当你想传递一个头字典时,你可以将该字典作为返回元组的第二个元素传递:
@app.post('/pets')
@app.input(PetIn)
@app.output(PetOut, status_code=201)
def create_pet(data):
# ...
# equals to:
# return pet, 201, {'FOO': 'bar'}
return pet, {'FOO': 'bar'}
使用@app.auth_required来保护你的视图
基于Flask-HTTPAuth,APIFlask提供了三种类型的身份验证:
HTTP Basic
要实现HTTP基本身份验证,你需要:
- 使用
HTTPBasicAuth创建一个auth对象 - 使用
@auth.verify_password注册一个回调函数,该函数应接受username和password,并返回相应的用户对象或None。 - 使用
@app.auth_required(auth)保护视图函数。 - 在视图函数中使用
auth.current_user访问当前用户对象。
from apiflask import APIFlask, HTTPBasicAuth
app = APIFlask(__name__)
auth = HTTPBasicAuth() # create the auth object
@auth.verify_password
def verify_password(username, password):
# get the user from the database, check the password
# then return the user if the password matches
# ...
@app.route('/')
@app.auth_required(auth)
def hello():
return f'Hello, {auth.current_user}!'
HTTP Bearer
要实现HTTP Bearer身份验证,你需要:
- 使用
HTTPTokenAuth创建一个auth对象 - 使用
@auth.verify_token注册一个回调函数,该函数应接受令牌,并返回相应的用户对象或None。 - 使用
@app.auth_required(auth)保护视图函数。 - 在视图函数中使用
auth.current_user访问当前用户对象。
from apiflask import APIFlask, HTTPTokenAuth
app = APIFlask(__name__)
auth = HTTPTokenAuth() # create the auth object
# or HTTPTokenAuth(scheme='Bearer')
@auth.verify_token # register a callback to verify the token
def verify_token(token):
# verify the token and get the user id
# then query and return the corresponding user from the database
# ...
@app.get('/')
@app.auth_required(auth) # protect the view
def hello():
# access the current user with auth.current_user
return f'Hello, {auth.current_user}'!
API密钥(在header)
类似于Bearer类型,但在创建auth对象时将方案设置为ApiKey:
from apiflask import HTTPTokenAuth
HTTPTokenAuth(scheme='ApiKey')
或使用自定义头:
from apiflask import HTTPTokenAuth
HTTPTokenAuth(scheme='ApiKey', header='X-API-Key')
# ...
您可以使用HTTPBasicAuth和HTTPTokenAuth中的description参数来设置OpenAPI安全描述。
请参阅Flask-HTTPAuth的文档以了解详细信息。但是,请记住从APIFlask导入HTTPBasicAuth和HTTPTokenAuth,并对视图函数使用@app.auth_required而不是@auth.login_required。