首页  >  文章  >  后端开发  >  如何在没有 Swagger UI 的情况下将 JSON 数据发送到 FastAPI 端点?

如何在没有 Swagger UI 的情况下将 JSON 数据发送到 FastAPI 端点?

Patricia Arquette
Patricia Arquette原创
2024-10-24 02:32:02448浏览

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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn