在python中使用fastapi入门
时间: 2024-04-19 21:05:21 浏览: 27
FastAPI 是一个基于 Python 的现代 Web 框架,它可以帮助我们快速构建高性能的 API。下面是使用 FastAPI 的入门指南:
1. 安装 FastAPI 和 uvicorn
```
pip install fastapi
pip install uvicorn[standard]
```
2. 创建一个 FastAPI 应用
```python
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
```
3. 运行应用
```bash
uvicorn main:app --reload
```
4. 测试 API
在浏览器中访问 `http://localhost:8000/`,应该会看到以下输出:
```json
{"message": "Hello World"}
```
5. 添加其他路由和操作
```python
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
```
在浏览器中访问 `http://localhost:8000/items/42?q=test`,应该会看到以下输出:
```json
{"item_id": 42, "q": "test"}
```
这只是 FastAPI 的一个简单入门指南,更多的功能和用法可以参考官方文档。
相关推荐
![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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)