quick start
安装
pip install fastapi
# ASGI服务器,生成环境可以使用uvicorn
pip install uvicorn
代码
from fastapi import FastAPI
import uvicorn
# 创建一个app实例
app = FastAPI()
# 编写一个路径操作装饰器
@app.get("/")
# 编写一个路径操作函数
async def home():
# 定义返回值
return {"user_id": 10001}
运行服务器
uvicorn fastapi_quick_start:app --reload
INFO: Will watch for changes in these directories: ['C:\\code\\vs_code_py\\fastapi']
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [2128] using WatchFiles
INFO: Started server process [29052]
INFO: Waiting for application startup.
也可以直接运行
from fastapi import FastAPI
import uvicorn
app = FastAPI()
@app.get("/")
async def home():
return {"user_id": 10001}
if __name__ == '__main__':
uvicorn.run("fastapi_quick_start:app", port = 8080, reload = True)
跳转到http://127.0.0.1:8080/docs,就可以看到自动生成的交互式api文档。