1.请求参数附加信息
#!/usr/bin/env python
# encoding: utf-8
from fastapi import FastAPI, Query
from typing import Optional
import uvicorn
app = FastAPI()
@app.get('/items/')
async def read_items(q: Optional[str] = Query(None, min_length=3, max_length=50)):
results = {'message': 'item'}
if q:
results.update({'q': q})
return results
if __name__ == '__main__':
uvicorn.run(app=app, host='127.0.0.1', port=8000)
使用Query作为默认值, 将参数设置min_length为3,max_length为50
添加正则表达式 q: Optional[str] = Query(None, regex="^fixedquery$")
设置默认值 q: str = Query("fixedquery", min_length=3)
title:参数标题
description:参数描述信息
deprecated:表示参数即将过期
alias:参数别名
当不需要声明更多的验证或元数据时,q只需不声明默认值即可使查询参数成为必需:q: str,
当使用Query声明它时,可以将...用作第一个参数,代表必填 eg: q: str = Query(..., min_length=3)
@app.get('/items/')
async def read_item(q: str = Query(..., min_length=3)):
"""使用Query声明它时,可以将...用作第一个参数"""
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results
2.请求参数列表
#!/usr/bin/env python
# encoding: utf-8
from fastapi import FastAPI, Query
from typing import Optional, List
import uvicorn
app = FastAPI()
@app.get('/items_list/')
async def read_item_list(q: Optional[List[str]] = Query(None)):
query_items = {"q": q}
return query_items
if __name__ == '__main__':
uvicorn.run(app=app, host='127.0.0.1', port=8000)
访问:http://localhost:8000/items/?q=foo&q=bar
得到结果:{"q": ["foo", "bar"]}
(1).请求参数列表的缺省值设置:q: List[str] = Query(["foo", "bar"])
(2).可以用list代替List[str],但这样的话FastAPI就无法校验列表内容了: q: list = Query(None)
3. 路径参数附加信息
#!/usr/bin/env python
# encoding: utf-8
from fastapi import FastAPI, Query, Path
from typing import Optional
import uvicorn
app = FastAPI()
@app.get('/item_path/{item_id}')
async def read_items_path(
item_id: int = Path(..., title='The ID of the item to get'),
q: Optional[str] = Query(None, alias='item-query'),
size: float = Query(1, gt=0, lt=10.5)
):
"""
路径参数附加信息
路径参数在URL里是必选的,因此Path的第一个参数是...,即使你传递了None或其他缺省值,也不会影响参数的必选性。
"""
results = {'item_id': item_id, 'size': size}
if q:
results.update({"q": q})
return results
if __name__ == '__main__':
uvicorn.run(app=app, host='127.0.0.1', port=8000)
4. 混合Path
,Query
和body参数
#!/usr/bin/env python
# encoding: utf-8
from fastapi import FastAPI, Query, Path
import uvicorn
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
"""
(1).如果把带有缺省值的参数放在了不带缺省值的参数前面,Python会发出运行警告。
因此在实际使用时,我们应当把不带缺省值的参数放在前面,无论这个参数是路径参数还是请求参数。
query: str, item_id: int = Path(..., title="The ID of the item to get")
(2).通过传递 * 作为第一个参数,就解决了上面的参数顺序问题。
*, item_id: int = Path(..., title="The ID of the item to get"), q: str
"""
@app.post('/body/{item_id}')
async def body(
query: str,
item_id: int = Path(..., title='', ge=10, le=100),
item: Item = None
):
result = {'item_id': item_id}
if query:
result.update({"query": query})
if item:
result.update({"item": item})
return result
if __name__ == '__main__':
uvicorn.run(app)
5. 多body
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
class User(BaseModel):
username: str
full_name: Optional[str] = None
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item, user: User):
results = {"item_id": item_id, "item": item, "user": user}
return results
响应参数:
6. body 的奇异值
from typing import Optional
from fastapi import Body, FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
class User(BaseModel):
username: str
full_name: Optional[str] = None
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item, user: User, importance: int = Body(...)):
results = {"item_id": item_id, "item": item, "user": user, "importance": importance}
return results
以上相当于将importance 参数 与User Item 组合起来形成一个大的body
7. 嵌入单一body
from typing import Optional
from fastapi import Body, FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item = Body(..., embed=True)):
results = {"item_id": item_id, "item": item}
return results
item: Item = Body(..., embed=True)
这里"item"是Request Body内部数据内容的键值,那么我们就需要利用Body方法的embed参数,才能正确解析出Request Body内容。使用后参数形式为:
{
"item": {
"name": "Foo",
"description": "The pretender",
"price": 42.0,
"tax": 3.2
}
}
8. body 内参数验证 Feild
需注意的:Feild 是基于pydantic 导出的
from typing import Optional
from fastapi import Body, FastAPI
from pydantic import BaseModel, Field
app = FastAPI()
class Item(BaseModel):
name: str
description: Optional[str] = Field(
None, title="The description of the item", max_length=300
)
price: float = Field(..., gt=0, description="The price must be greater than zero")
tax: Optional[float] = None
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item = Body(..., embed=True)):
results = {"item_id": item_id, "item": item}
return results