安裝模塊
# 一個現代的,快速(高性能)python web框架
pip install fastapi
# 主要用於加載和提供應用程序的服務器.
pip install uvicorn
運行代碼
import uvicorn as uvicorn
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI() # 必須實例化該類,啟動的時候調用
class People(BaseModel): # 必須繼承
name: str
age: int
address: str
salary: float
# 請求根目錄
@app.get('/')
def index():
return {'message': '歡迎來到FastApi 服務!'}
# get請求帶參數數據
@app.get('/items/{item_id}')
def items(item_id: int):
return {'message': '歡迎' + item_id + '來到接口頁面'}
# post請求帶參數數據
@app.post('/people')
def insert(people: People):
age = people.age
msg = f'名字:{people.name},年齡:{age}'
return {'success': True, 'msg': msg}
if __name__ == '__main__':
uvicorn.run(app=app, host="127.0.0.1", port=8080)
運行命令
uvicorn main:app --reload
快速文檔
http://127.0.0.1:8000/docs
http://127.0.0.1:8000/redoc
更多內容:https://fastapi.tiangolo.com/zh/