如何將 JSON 資料直接發佈到 FastAPI 後端?

Mary-Kate Olsen
發布: 2024-10-24 04:16:02
原創
570 人瀏覽過

How to Post JSON Data Directly to a FastAPI Backend?

直接發佈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中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!