Python|Build FARM Stack App|2. FastAPI

y
chenstraveler
Published in
8 min readDec 7, 2021
20170108 / 北海道 / photo: chenstraveler

🚀 官方文件

FastAPI framework, high performance, easy to learn, fast to code, ready for production.

🚀 為何選擇 FastAPI

大約是今年(2021) 一月開始接觸Python後端開發,使用過Django、Falsk,為了加速開發時間,第一次嘗試使用FastAPI,發現開發時間真的加速很多,而且官方文件也寫得很清楚。

優點:

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.

  • Fast(快速): 可與NodeJSGo 比肩的極高性能(歸功於 Starlette 和Pydantic)。最快的 Python web 框架之一
  • Fast to code(高效編碼): 提高功能開發速度约 200% 至 300%。
  • Fewer bugs(更少 bug): 減少約40% 的人為(開發者)導致錯誤。
  • Intuitive(智能): 極佳的編輯器支持。處處皆可自動補全,減少調試時間。
  • Easy(簡單): 設計得易於使用和學習,閱讀文檔的時間更短。
  • Short(簡短): 使代碼重複最小化。通過不同的參數聲明實現豐富功能。bug 更少。
  • Robust(健壯): 生產可用級別的代碼。還有自動生成的交互式文檔。Standards-based(標準化): 基於(並完全兼容)API 的相關開放標準:OpenAPI (以前被稱為 Swagger) 和JSON Schema

🚀 Requirements

Python 3.6或以上的版本。

FastAPI 站在以下巨人的肩膀之上:

🚀 安裝

1. 安裝最新版本套件

Step1: 初始化專案(如果還沒有pyproject.toml文件,如有可跳過)

$ poetry init

Step2. 安裝 fastapi & uvicorn((ASGI服務器)

$ poetry fastapi
$ poetry uvicorn

Step3. 安裝完成後會得到 pyproject.toml & poetry.lock兩個檔案

# pyproject.toml[tool.poetry]
name = "fastapi_with_mongodb"
version = "0.1.0"
description = "FastAPI with MongoDB"
authors = ["chenstraveler <chenstraveler@gmail.com>"]
[tool.poetry.dependencies]
python = "^3.8"
fastapi = "^0.70.0"
uvicorn = "^0.15.0"
[tool.poetry.dev-dependencies][build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

Step4. 進入虛擬環境,進行開發。

$ poetry shell

2. 指定安裝套件版本

Step1: 手動設定pyproject.toml 中 [tool.poetry.dependencies] 參數

Step2: 進行安裝

$ poetry install

Step3. 進入虛擬環境,進行開發。

$ poetry shell

🚀 如何使用 FastAPI

Step1. Create FastAPI

  • 建立一個app資料夾
  • 加入一個空的檔案:__init__.py
  • 加入主程式:main.py
.
├── app
│ ├── __init__.py
│ ├── main.py

Step2. Run FastAPI

$ uvicorn main:app --reload

Step3. Check status via Brower

使用瀏覽器訪問:http://127.0.0.1:8000/items/5?q=somequery

將會看到如下JSON響應:

你已經創建了一個具有以下功能的API:

  • 通過 path//items/{item_id} 接受 HTTP 請求。
  • 以上 path 都接受 GET 操作(也被稱為 HTTP 方法)。
  • /items/{item_id} path 有一个 路徑參數 item_id 並且應該為 int 類型。
  • /items/{item_id} path有一個可選的 str 類型的 查詢參數q

Step4. OpenAPI document (Swagger UI介面)

OpenAPI document: http://127.0.0.1:8000/docs

你會看到自動生成的交互式API文檔案(由 Swagger UI生成)

🚀 客製化Swagger UI

Self-hosting(自託管) JavaScript and CSS for docs

官方文件:Self-hosting JavaScript and CSS for docs

API docs包含了SwaggerUI和ReDoc,這兩個檔案都包含了JavaScript 和 CSS files。在FastAPI服務中的預設,這些檔案是透過CDN取得的。

如果想要客製化Swagger UI頁面,或是你的app需要離線瀏覽、或是需要在內網環境使用的話。也可以使用以下的方法來製作自己的Swagger UI:

下載static files檔案

Step1: 假設目前你的專案結構如下:

.
├── app
│ ├── __init__.py
│ ├── main.py

Step2: 新增一個資料夾

為了存放JavaScript and CSS檔案(static files),新增後專案結構如下:

.
├── app
│ ├── __init__.py
│ ├── main.py
└── static/

Step3: 下載JavaScript and CSS檔案

Swagger UI uses the files:

And ReDoc uses the file:

.
├── app
│ ├── __init__.py
│ ├── main.py
└── static
├── redoc.standalone.js
├── swagger-ui-bundle.js
└── swagger-ui.css

使用static files檔案

對應 main.py #8 & #14

  • Import StaticFiles.
  • “Mount” a StaticFiles() instance in a specific path.

關閉自動docs設定

對應 main.py #11

預設會使用 CDN服務。第一步先關閉自動docs設定:

  • set their URLs to None when creating your FastAPI app.

加入自定義文檔

對應 main.py #2~#6 & #18~$40

  • 可以重複使用 FastAPI的internal functions,藉由傳遞不同參數成為自定義的Swagger UI。
  • openapi_url: the URL where the HTML page for the docs can get the OpenAPI schema for your API. You can use here the attribute app.openapi_url.
  • title: the title of your API.
  • oauth2_redirect_url: you can use app.swagger_ui_oauth2_redirect_url here to use the default.
  • swagger_js_url: the URL where the HTML for your Swagger UI docs can get the JavaScript file. This is the one that your own app is now serving.
  • swagger_css_url: the URL where the HTML for your Swagger UI docs can get the CSS file. This is the one that your own app is now serving.

main.py example

其他更多設定 & 功能可參考FastAPI官方document

下一篇介紹如何基於Poetry文件 Dockerize FastAPI。

--

--