直接發佈JSON 資料到FastAPI 後端
問題陳述:
解決方案:
為了實現這一點,JavaScript 函式庫(例如 Fetch API)可以就業。這些工具可以傳送 JSON 格式的資料。
對於前端渲染,Jinja2Templates 可用於傳回包含 HTML 和 JavaScript 程式碼的範本。也可以直接發布 JSON 數據,如下面的程式碼範例所示。app.py
templates/index.html
<code class="python">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})</code>
透過這種方法,您可以直接將JSON 資料發佈到FastAPI 後端,而無需依賴Swagger UI。資料可以透過前端的表單提交並由後端 API 處理。
以上是如何將 JSON 資料直接發佈到 FastAPI 後端?的詳細內容。更多資訊請關注PHP中文網其他相關文章!