安装FastAPI
pip install fastapi
test1.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):#路由处理函数中的q是查询参数,可以在请求URL中使用,例如/items/42?q=somequery
return {"item_id": item_id, "q": q}
#自动生成接口文档:http://127.0.0.1:8000/docs
vscode 终端里执行:uvicorn test1:app --reload 启动服务
访问:
http://127.0.0.1:8000/items/42?q=somequery
如果需要使用FastAPI的自动文档和交互式API页面功能,还需要安装uvicorn和[optional] python-multipart:
pip install uvicorn[standard]
pip install python-multipart
自动生成接口文档 http://127.0.0.1:8000/docs
这里刚开始 有个报错:raise PydanticImportError(f’{import_path}
has been removed in V2.')
pydantic.errors.PydanticImportError: pydantic.error_wrappers:ErrorWrapper
has been removed in V2.
解决方案:
只要把 pydantic版本降级1.10.2,
pip install pydantic==1.10.2