查询参数

声明的不在路径参数中的变量会被归为查询参数,查询参数拼接在url中,格式为:

1
127.0.0.1:8000/query_route?key1=value1&key2=value2

?起始,多个参数之间用&连接
类似路径参数的Path,查询参数可用Query约束,Query的参数与Path相同
在代码中定义查询参数:

1
2
3
4
5
6
7
from fastapi import FastAPI,Query

app = FastAPI()

@app.get("/query")
async def get_query(id : str = Query(max_lenght = 10)):
return {'msg':f'You are querying {id}'}

查询参数可规定默认值:

1
2
3
4
5
6
7
8
9
from fastapi import FastAPI,Query

app = FastAPI()

@app.get("/query")
async def get_query(id : int = 10 , class_ : str = Query("que",min_lenght = 2)):

return {"msg":f"You are query id:{id},class:{class_}"}

在此情况下访问127.0.0.1:8000/query将得到与127.0.0.1:8000/query?id=10&class_=que同样的结果

注意:如果你定义了查询参数而没有规定默认值,那么url中该参数是必须的,你必须在url中拼接该参数,否则将报错

请求体参数

通过post方法发送带参数的请求,请求体用继承自pydentic.BaseModel的类定义
类似Path、Query,请求体参数可以用pydentic.Field约束:

1
2
3
4
5
6
7
8
9
10
11
12
13
from fastapi import FastAPI
from pydantic import BaseModel ,Field

app = FastAPI()

class User(BaseModel):
uid : str = Field(max_length=20,min_length=1)
password: str = Field(min_length=8,max_length=20)


@app.post("/register")
async def register(user:User):
return user

响应类型

可通过修改装饰器中的response_class参数改变响应类型,默认值是JSONResponse,可选值还包括ResponseHTMLResponsePlainTextResponse(纯文本)、FileResponseStreamingResponseRedirectResponse(重定向)

1
2
3
4
5
6
7
8
from fastapi import FastAPI
from fastapi.responses import HTMLResponse,PlainTextResponse

app = FastAPI()

@app.get("/",response_class=PlainTextResponse)
async def root():
return '<h1>Hello World</h1>'

FastAPI还支持自定义响应数据格式,响应类需继承自pydentic.BaseModel:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class CustomResponse(BaseModel):
id:int
message:str

@app.get("/",response_model=CustomResponse)
async def root():
return {
'id' : 500,
'message': 'Hello World'
}

返回值必须严格契合自定义的格式,否则会报错

异常处理

FastAPI的异常处理靠fastapi.HTTPException实现,HTTPException有三个参数status_codedetailsheaders(自定义响应头):

1
2
3
4
5
6
7
8
9
10
11
from fastapi import FastAPI,HTTPException

app = FastAPI()

@app.get("/{item}")
async def read_item(item:int):
item_list = [1,2,3,4,5,6,7,8,9,10]
if item not in item_list:
raise HTTPException(status_code=404,detail="Item not existed")

return {"item":item}