python fastapi 示例

源代码
from fastapi import FastAPI
from pydantic import BaseModel
import uvicorn


app = FastAPI() #实例化FastAPI


class Item(BaseModel):
    name: str
    price: float
    is_offer: bool = None


'''
{
  "named": "string",
  "price": 0,
  "is_offer": true
}
'''


@app.get("/")
async def read_root():
    return {"Hello": "World"}


@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str = None):  # 此处q为query的字段
    return {"item_id": item_id, "q": q}


@app.post("/items/{item_id}")
async def update_item(item_id: int, item: Item):  # 此处Item为body的schema
    return {"item_name": item.name, "item_id": item_id}


if __name__ == '__main__':
    uvicorn.run('main:app',port=8080)

posted @ 2020-07-18 17:29  办公魔盒  阅读(1083)  评论(0)    收藏  举报