FastAPI的作用:把函数 / 模型包装成HTTP 接口,供前端或其他服务调用。(和Java中Spring Boot写接口的作用是一样的)
官方文档:FastAPI官方文档
安装:
bash
pip intsall fastapi
python
pip install "fastapi[standard]"
使用步骤:
- 导入FastAPI
python
from fastapi import FastAPI
-
创建FastAPI实例对象
-
创建路径操作函数,定义访问路径
python
app = FastAPI()
@app.get("/")
def test1():
return ("hello world!")
- 运行FastAPI服务
运行命令:
-
方式一(FastAPI CLI 命令):
pythonfastapi dev "xxxx.py" -
方式二(uvicorn 直接运行):
python# 启动服务 if __name__ == "__main__": import uvicorn uvicorn.run(app,host="127.0.0.1",port=8000)