透過使用這些技術,您可以輕鬆地將 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"}}
」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在沒有 Swagger UI 的情況下向 FastAPI 提交 JSON 資料?

如何在沒有 Swagger UI 的情況下向 FastAPI 提交 JSON 資料?

發佈於2024-11-07
瀏覽:868

How to Submit JSON Data to FastAPI without Swagger UI?

在 FastAPI 中繞過 Swagger UI 進行 JSON 資料輸入

使用 FastAPI 時,可以在沒有 Swagger UI 中介的情況下發布 JSON 資料。實現此目的的方法如下:

用於 JSON 資料提交的 JavaScript 介面

採用基於 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
});

HTML 表單和 Jinja2 範本

或者,您可以使用 Jinja2 範本和 HTML 表單來提交資料。方法如下:

app.py

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})

index.html

透過使用這些技術,您可以輕鬆地將 JSON 資料發佈到 FastAPI 後端,而無需依賴 Swagger UI 介面。

版本聲明 本文轉載於:1729684541如有侵犯,請洽[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3