Deploy Easy API Fastly - FastAPI
David / 2022-06-22
Table of Contents
最近在學新的前端東西,想說很久以前就聽過 FastAPI ,所以來試著做出一個簡單的後端,就點開了 FastAPI 的專案,意外發現這個超好用、超方便的 API Lib!
創立本機專案
首先安裝 FastAPI library pip install "fastapi[all]" ,完成後新增一個 main.py 檔案,並在裡面寫出這樣的 code:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}並在 terminal 輸入 uvicorn main:app --reload 就完成本機伺服器的架設,點開http://127.0.0.1:8000 就可以看到 Hello World 的 Json 訊息囉!
建立路徑
我們可以新增一筆紀錄來擴充一支 route ,也可以很簡單的取得 Param。
@app.get("/items/{item_id}")
async def read_item(item_id):
return {"item_id": item_id}而 post 則可以使用 @app.get("/items/{item_id}") 來作為入口。
要支援多 method 也可以使用 @app.api_route("/", methods=["GET", "POST", "OPTIONS"]) 來擴充。
取得 Request Body
都支援了 POST request,總要能讀到 body 裡傳的資訊吧!我們可以新建一個 class 來完成這件事。
from pydantic import BaseModel
class b(BaseModel):
by: int
@app.post("/increment")
async def increment(b: b):
number += int(b.by)
return {"number": number}這上面就是一個簡單的 post api,可以接收到 body 傳的以下 Json :
{
"by": 100
}部署至雲端服務(使用 Vercel)
以上完成之後我們要再新增一個 vercel.json 檔案,上傳至 guthub 並完成連結之後他就會自動讀到這個檔案然後幫你建制並發布完成。
{
"builds": [
{"src": "/main.py", "use": "@vercel/python"}
],
"routes": [
{"src": "/(.*)", "dest": "main.py"}
]
}心得
今天我們學到了如何超快速的建好簡單的後端伺服器並完成部署,過程甚至不用十分鐘,真的是 FastAPI!