如何在沒有 Swagger UI 的情況下將 JSON 資料傳送到 FastAPI 端點?

Patricia Arquette
發布: 2024-10-24 02:32:02
原創
456 人瀏覽過

How to Send JSON Data to FastAPI Endpoints without Swagger UI?

繞過Swagger UI 以在FastAPI 發布JSON 資料

雖然Swagger UI (OpenAPI) 提供了一種測試API 端點的便捷方法,但在某些情況下您可能需要直接發送JSON 資料而不使用它。本文提供了一個使用 JavaScript 介面將 JSON 資料發佈到 FastAPI 端點的解決方案。

為了實現這一點,我們將利用 Fetch API,它允許以 JSON 格式發送資料。此外,我們將使用 Jinja2Templates 為前端建立一個範本。

後端實作

在app.py 中,FastAPI 應用程式使用/ 端點定義,該端點接受帶有Item 模型的POST 請求.

<code class="python">from fastapi import FastAPI, Request, HTTPException
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    roll: int

app = FastAPI()
templates = Jinja2Templates(directory="templates")

@app.post("/")
async def create_item(item: Item):
    if item.name == "bad request":
        raise HTTPException(status_code=400, detail="Bad request.")
    return item

@app.get("/")
async def index(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})</code>
登入後複製

前端實作

在index.html範本中,提供了一個HTML表單用於輸入姓名和磁碟區資料。 SubmitForm() 函數使用 Fetch API 以 JSON 形式傳送資料。

<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())
        .then(data => {
          document.getElementById("responseArea").innerHTML = data;
        })
        .catch(error => {
          console.error(error);
        });
      }
    </script>
  </body>
</html></code>
登入後複製

用法

導覽至 http://localhost:8080/ 以存取前端。在表格中輸入資料並點擊“提交”按鈕。來自 / 端點的回應將顯示在 HTML 的「responseArea」div 中。

請注意,您可以使用 .catch() 方法在 JavaScript 程式碼中處理端點拋出的異常,如下所示在範例中。

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

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