python+uvicorn+fastapi (二) - 最簡單的post請求


路徑參數

路徑參數 item_id 的值將作為參數 item_id 傳遞給你的函數。

from fastapi import FastAPI

app = FastAPI()

@app.get("/case/{cid}")
def read_case(cid):
    return {"id": cid}

如果你運行示例並訪問 http://127.0.0.1:8002/case/foo,將會看到如下響應:

{"id":"foo"}

數據轉換

如果你訪問 http://127.0.0.1:8002/case/1,將會看到如下響應

{"id":1}

有類型的路徑參數

@app.get("/items/{item_id}")
def read_item1(item_id: int, q: Optional[str] = None):
    return {"item_id": item_id, "q": q}

如果你訪問http://127.0.0.1:8002/items/100?q=1,將會看到如下響應

{"item_id":100,"q":"1"}

數據校驗

如果訪問http://127.0.0.1:8002/items/foo?q=1,會看到如下響應

{
	"detail": [
		{
			"loc": [
				"path",
				"item_id"
			],
			"msg": "value is not a valid integer",
			"type": "type_error.integer"
		}
	]
}

因為路徑參數 item_id 傳入的值為 "foo",它不是一個 int

Pydantic

所有的數據校驗都由 Pydantic 在幕后完成

查詢參數

聲明不屬於路徑參數的其他函數參數時,它們將被自動解釋為"查詢字符串"參數

from fastapi import FastAPI

app = FastAPI()

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]

查詢字符串是鍵值對的集合,這些鍵值對位於 URL 的 之后,並以 & 符號分隔。

例如,在以下 url 中:

http://127.0.0.1:8000/items/?skip=0&limit=10

...查詢參數為:

  • skip:對應的值為 0,這里是代碼指定的默認值
  • limit:對應的值為 10,這里是代碼指定的默認值

請求體

你的 API 幾乎總是要發送響應體。但是客戶端並不總是需要發送請求體。

我們使用 Pydantic 模型來聲明請求體,並能夠獲得它們所具有的所有能力和優點。

這里要注意一點:

你不能使用 GET 操作(HTTP 方法)發送請求體。

要發送數據,你必須使用下列方法之一:POST(較常見)、PUTDELETEPATCH

DEMO

數據模型繼承自pydantic的BaseModel,Pydantic 會幫你處理模型內定義的字段的數據校驗的問題。

from typing import Optional

from fastapi import FastAPI
from pydantic import BaseModel


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


app = FastAPI()

@app.get("/items/{item_id}")
def read_item1(item_id: int, q: Optional[str] = None):
    return {"item_id": item_id, "q": q}

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

示例代碼包含一個get請求一個post請求,在pycharm上看到數據模型Item的內容會有紅色波浪線,不要緊,不會影響程序運行。

我們訪問http://127.0.0.1:8002/items/1?q=123,可以看到get請求的響應如下

{"item_id":1,"q":"123"}

然后再發送一個post請求看下響應,post請求的url和請求體可以這樣寫

url

http://127.0.0.1:8002/items/

body

{   
    "name": "kpc測試商品",
    "description": "我是偉大的post接口描述",
    "price": 100.00,
    "tax": "0.13"
}

響應的內容如下

{
    "name": "kpc測試商品",
    "description": "我是偉大的post接口描述",
    "price": 100.0,
    "tax": 0.13
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM