首頁  >  文章  >  後端開發  >  如何在沒有 Swagger UI 的情況下將 JSON 資料發佈到 FastAPI?

如何在沒有 Swagger UI 的情況下將 JSON 資料發佈到 FastAPI?

Patricia Arquette
Patricia Arquette原創
2024-10-24 05:26:02779瀏覽

How to Post JSON Data to FastAPI Without Swagger UI?

在沒有Swagger UI 的情況下將JSON 資料發佈到FastAPI

使用FastAPI 時,了解如何在不使用Swagger UI 的情況下將JSON 資料發佈到其後端非常有用依賴Swagger UI。這種方法允許透過指定的 URL 直接發布資料並在瀏覽器中檢索結果。

使用 Javascript 接口

要實現這一點,您可以實現Javascript 接口,例如 Fetch API,可以以 JSON 格式提交資料。考慮以下程式碼範例:

<code class="javascript">body: JSON.stringify({name: "foo", roll: 1})</code>

此程式碼片段將 Javascript 物件轉換為 JSON 進行傳輸。

前端實作

與在FastAPI 後端,您可以利用以下方法之一:

  • Jinja2Templates
  • Jinja2Templates :此技術涉及渲染包含用於提交資料的表單的HTML/JS 範本。然後可以將表單資料轉換為 JSON。
直接 JSON 發布

:使用 Fetch API,您可以直接發布 JSON 數據,而無需涉及表單。

範例實作

考慮以下Python 中的範例實作:

<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>
app.py

app.py
<code class="html"><!DOCTYPE html>
<html>
   <body>
      <h1>Post JSON Data</h1>
      <form method="post" id="myForm">
         name : <input type="text" name="name" value="foo">
         roll : <input type="number" name="roll" value="1">
         <input type="button" value="Submit" onclick="submitForm()">
      </form>
      <div id="responseArea"></div>
      <script>
         function submitForm() {
             var formElement = document.getElementById('myForm');
             var data = new FormData(formElement);
             fetch('/', {
                   method: 'POST',
                   headers: {
                     'Accept': 'application/json',
                     'Content-Type': 'application/json'
                 },
                   body: JSON.stringify(Object.fromEntries(data))
                 })
                 .then(resp => resp.text())  // or, resp.json(), etc.
                 .then(data => {
                   document.getElementById("responseArea").innerHTML = data;
                 })
                 .catch(error => {
                   console.error(error);
                 });
         }
      </script>
   </body>
</html></code>

app.pyapp.pyapp.pyapp.pyapp.pyapp.pyapp。 🎜> templates/index.html透過執行下列步驟,您可以有效地將JSON 資料發佈到FastAPI 後端,而無需Swagger UI。這種方法允許更大的靈活性,並透過指定的 URL 與後端直接互動。

以上是如何在沒有 Swagger UI 的情況下將 JSON 資料發佈到 FastAPI?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn