FastAPI 01 Create Demo
- [install package](#install package)
- [创建 hello_world.py](#创建 hello_world.py)
- [启动命令 `uvicorn hello_world:app --reload`](#启动命令
uvicorn hello_world:app --reload) - 可用的URL
install package
pip install fastapi uvicorn
创建 hello_world.py
py
from fastapi import FastAPI
# 创建一个 FastAPI 实例
app = FastAPI()
# 定义一个路由
@app.get("/")
def root():
return {
"Hello World": "this is FastAPI",
}
if __name__ == "__main__":
import uvicorn
from pathlib import Path
this_file = Path(__file__).absolute().resolve()
this_file_stem = this_file.stem
uvicorn.run(
f'{this_file_stem}:app',
host="127.0.0.1",
port=8000,
reload=True,
)
启动命令 uvicorn hello_world:app --reload
cmd
launcher 6229 -- -m uvicorn hello_world:app --reload "
INFO: Will watch for changes in these directories: ['E:\\workspace\\python\\hugh_fastapi']
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [23296] using StatReload
INFO: Started server process [24388]
INFO: Waiting for application startup.
INFO: Application startup complete.
可用的URL
FastAPI 的强大之处在于它默认提供了交互式 API 文档。启动服务后,你可以在浏览器中直接访问以下两个内置 URL:
-
Swagger UI (交互式文档,最常用):
在这里你可以直接在网页上点击 "Try it out" 测试你的
/items/{item_id}接口。 -
ReDoc (另一种风格的文档):
-
根路径 URL