FastAPI使用记录

背景

FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架 , 可以用来创建用于获取预测结果的 REST 服务

安装

pip install fastapi
pip install "uvicorn[standard]"

使用

GET

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
def root():
    return {"message": "Hello World"}

#  ------------------------------------------ Path parameters  ------------------------------------------
@app.get("/items/{item_id}")
def read_item(item_id: int):
    return {"item_id": item_id}


# ------------------------------------------ Query Parameters  ------------------------------------------
# The query is the set of key-value pairs that go after the ? in a URL, separated by & characters.
# http://127.0.0.1:8000/items/?skip=0&limit=10
fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]

@app.get("/items/")
def read_item(skip: int = 0, limit: int = 10):
    return fake_items_db[skip : skip + limit]

#  ------------------------------------------ HTMLResponse  ------------------------------------------
from fastapi.responses import HTMLResponse

@app.get("/test/", response_class=HTMLResponse)
async def read_items():
    return """
    <html>
        <head>
            <title>Some HTML in here</title>
        </head>
        <body>
            <h1>Look ma! HTML!</h1>
        </body>
    </html>
    """

#  ------------------------------------------ FileResponse  ------------------------------------------

from fastapi.responses import FileResponse
some_file_path = "large-video-file.mp4"

@app.get("/file")
async def main():
    return FileResponse(some_file_path)

POST

from typing import Union

from fastapi import FastAPI
from pydantic import BaseModel


class Item(BaseModel):
    name: str
    description: Union[str, None] = None
    price: float
    tax: Union[float, None] = None


app = FastAPI()

@app.post("/items/")
def create_item(item: Item):
    return item

from fastapi import FastAPI, File, UploadFile

@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile):
    return {"filename": file.filename}

Know More About async def

https://fastapi.tiangolo.com/async/#in-a-hurry

Responses

from fastapi.responses import HTMLResponse
from fastapi.responses import FileResponse
from fastapi.responses import StreamingResponse

RUN

uvicorn main:app --reload

# http://127.0.0.1:8000
# http://127.0.0.1:8000/docs
# http://127.0.0.1:8000/redoc

# A "path" is also commonly called an "endpoint" or a "route".

Tips

按顺序执行,可以如此定义

from fastapi import FastAPI

app = FastAPI()


@app.get("/users/me")
async def read_user_me():
    return {"user_id": "the current user"}


@app.get("/users/{user_id}")
async def read_user(user_id: str):
    return {"user_id": user_id}

参考