透過使用這些技術,您可以輕鬆地將 JSON 資料發佈到 FastAPI 後端,而無需依賴 Swagger UI 介面。
","image":"http://www.luping.net/uploads/20241025/1729834590671b2e5e700bb.jpg","datePublished":"2024-11-07T00:35:56+08:00","dateModified":"2024-11-07T00:35:56+08:00","author":{"@type":"Person","name":"luping.net","url":"https://www.luping.net/articlelist/0_1.html"}}使用 FastAPI 時,可以在沒有 Swagger UI 中介的情況下發布 JSON 資料。實現此目的的方法如下:
採用基於 JavaScript 的介面(例如 Fetch API)以 JSON 格式傳送資料。這是一個例子:
var data = {
name: "foo",
roll: 1
}
fetch('/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then(resp => {
return resp.text();
}).then(data => {
// Handle the response
});
或者,您可以使用 Jinja2 範本和 HTML 表單來提交資料。方法如下:
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel
app = FastAPI()
templates = Jinja2Templates(directory="templates")
class Item(BaseModel):
name: str
roll: int
@app.post("/")
async def create_item(item: Item):
return item
@app.get("/")
async def index(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
透過使用這些技術,您可以輕鬆地將 JSON 資料發佈到 FastAPI 後端,而無需依賴 Swagger UI 介面。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3