FastAPI 介紹
FastAPI 是一個現代的 Python 網絡應用程式框架,設計用於建立高性能的 Web API。開發超級快速而且自動產生文件(Yes ! 以後都不用再寫文件了),到底有多快,下面 5 行就有一個簡單的 Web API。
file name: test.py
1
2
3
4
5
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def index():
return {"message": "Hello World! NBA 終於開打了!! 202310/25"} # it can return dict, list, str, int, etc.
加上指令 uvicorn test1:app --reload
特性
超快速:FastAPI 基於 Starlette 高性能 ASGI 框架,因此具有出色的性能,能夠處理大量並發請求。
強大的類型提示:FastAPI 使用 Python 3.6+ 的型別提示來定義 API 端點,這使得代碼具有良好的文檔、自動完成功能和靜態類型檢查。
自動文檔生成:FastAPI 可以根據代碼中的型別提示自動生成互動式文檔,這使得 API 的文檔保持最新且易於瀏覽。
身份驗證和授權:FastAPI 支持常見的身份驗證和授權方法,如基本身份驗證、OAuth、JWT 等,以確保 API 安全性。
cmd 示範
以下兩個檔案就可以 VSCode 建立 FastAPI 開發環境,建立環境開參考此篇
Dockerfile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Use an official Python runtime as a parent image
FROM python:3.9-slim-buster
# Set the working directory to /app
WORKDIR /app
# Copy the requirements file into the container at /app
COPY requirements.txt .
# Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir --upgrade pip && \
pip install --no-cache-dir -r requirements.txt && \
rm -rf /root/.cache/pip/*
# Copy the rest of the application code into the container at /app
COPY . .
# Expose the port that Django runs on
EXPOSE 8000
requirement.txt
等等,為什麼要載 uvicorn 的庫 ? 因為 FastAPI 沒有內建的開發 server, 使用 uvicorn 可以有 ASGI 、熱重載、多工作進程支持的好處。
1
2
fastapi
uvicorn
來看自動產生的文件吧
1
http://127.0.0.1:8000/docs
這文件還是互動式文件,可以在上面直接 call api,看看參數是否有錯,或是回傳值是否符合預期
我們會繼續玩 FastAPI, 到時候再看看可以做到什麼應用
We will see.