FastAPI: 请求体Query-Path-Body-Field(7)

多参数混用Path和Query

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Book(BaseModel):
name: str
price: float
description: Optional[str] = None

class Author(BaseModel):
name: str
address: Optional[str] = None

app = FastAPI()

@app.post('/authors/{id}')
def root(*,
id: int = Path(..., gt=12),
author: Author,
book: Book,
query: Optional[str] = Query(None)):

return id, author, book, query

Body实现请求体中单一值

在设定好的模型之外,想在发送请求时另外加一个字段进去,如果单独定义就会把它当成一个查询参数,可以利用Body来实现。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Book(BaseModel):
name: str
price: float
description: Optional[str] = None

class Author(BaseModel):
name: str
address: Optional[str] = None

app = FastAPI()

@app.post('/authors/{id}')
def root(*,
id: int = Path(..., gt=12),
author: Author,
book: Book,
publisher: str = Body(...),
query: Optional[str] = Query(None)):

return id, author, book, publisher, query

嵌入请求体参数

如果想把请求体外边再加一个字段来标识,也可以通过Body来实现

1
2
3
4
5
6
7
8
9
10
11
class Book(BaseModel):
name: str
price: float
description: Optional[str] = None

app = FastAPI()

@app.post('/books/')
def root(book: Book = Body(..., embed=True),
query: Optional[str] = None):

return book, query

Field校验模型里字段

1
2
3
4
5
6
7
8
9
10
11
class Book(BaseModel):
name: str = Field(..., min_length=2, max_length=10)
price: float
description: Optional[str] = None

app = FastAPI()

@app.post('/books/')
def root(book: Book = Body(..., embed=True),
query: Optional[str] = None):

return book, query

唐胡璐 wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
分享创造价值,您的支持将鼓励我继续前行!