python中fastapi框架的基本用法之get请求与post请求和参数路由等
Path
示例:a.com/path1/
Query
示例:a.com/?q=1
Body
from fastapi import Body, FastAPI, Form,Request,Query,Path
from typing import Optional, List, Tuple
from pydantic import BaseModel
import uvicorn
app666 = FastAPI()
# 文档参考:https://www.w3cschool.cn/fastapi/fastapi-body.html
# 示例1:GET
# http://127.0.0.1:8105/items/666
@app666.get("/items/{item_id}")
async def read_item(item_id: str, q: Optional[str] = None):
if q:
return {"item_id": item_id, "q": q}
return {"item_id": item_id}
# 示例2:POST
# http://127.0.0.1:8105/items/
# postman中的请求体,body,raw:
# {
# "name":111,
# "price":1.11
# }
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
@app666.post("/items/")
async def create_item(item: Item):
return item
app = app666
# http://127.0.0.1:8105/items/?q=1234567
# 限制长度5
@app.get("/items/")
async def read_items(q: Optional[str] = Query(None, max_length=5)):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results
# http://127.0.0.1:8105/items222/666?q=qqq
# https://www.w3cschool.cn/fastapi/fastapi-o6dx3lc6.html
# 在 Python 中,非默认参数不能在默认参数之后声明,
# 这就是为什么 IDE 给出了语法错误提示。
# 解决这个问题的方法是:将默认参数放在参数列表的最后,或者使用*号
# 错误:async def read_items(item_id: int = Path(..., title="The ID of the item to get"), q: str):
# 正确:async def read_items(q: str, item_id: int = Path(..., title="The ID of the item to get")):
# `...`表示这个参数是必需的,没有默认值。title="这是GET参数"是一个描述,没什么意义。所以等同于Path()
@app.get("/items222/{item_id}")
async def read_items(
*, item_id: int = Path(..., title="这是GET参数"), q: str
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
class User(BaseModel):
username: str # 必填
full_name: Optional[str] = None # 非必填
# 请求URL:http://127.0.0.1:8105/items333/1
# 请求参数:
# {
# "user":{"username":"a","full_name":"b"},
# "importance":1
# }
@app.post("/items333/{item_id}")
async def update_item(
item_id: int, user: User, importance: int = Body(...)
):
results = {"item_id": item_id, "user": user, "importance": importance}
return results
# 运行:
# 1 python main.py
# 2 文档:http://127.0.0.1:8105/docs
if __name__ == '__main__':
uvicorn.run(app='main:app666', host="0.0.0.0", port=8105, reload=True)