写一个post请求的fastapi
时间: 2023-07-07 16:44:27 浏览: 128
好的,以下是一个使用 FastAPI 编写的 POST 请求的示例代码:
```python
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
is_offer: bool = None
@app.post("/items/")
async def create_item(item: Item):
item_dict = item.dict()
if item.is_offer:
item_dict.update({"description": "Special offer"})
return item_dict
```
这个示例代码中,我们定义了一个 `Item` 类,它继承了 `BaseModel`,并定义了三个属性:`name`、`price` 和 `is_offer`。然后我们在 `create_item` 函数中,接收一个 `Item` 类型的参数 `item`,并返回它的字典形式。
我们使用 `@app.post("/items/")` 装饰器来定义一个 POST 请求的路由,路由地址为 `/items/`。当客户端向这个路由发送一个 POST 请求时,FastAPI 会自动将请求体中的 JSON 数据转换为 `Item` 类型的实例,并将它作为参数传递给 `create_item` 函数。
你可以根据自己的需求修改这个示例代码。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)