首页  >  文章  >  后端开发  >  如何在没有 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:此技术涉及渲染包含用于提交数据的表单的 HTML/JS 模板。然后可以将表单数据转换为 JSON。
  • 直接 JSON 发布:使用 Fetch API,您可以直接发布 JSON 数据,而无需涉及表单。

示例实现

考虑以下 Python 中的示例实现:

app.py

<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>

templates/index.html

<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>

通过执行以下步骤,您可以有效地将 JSON 数据发布到 FastAPI 后端,而无需 Swagger UI。这种方法允许更大的灵活性,并通过指定的 URL 与后端直接交互。

以上是如何在没有 Swagger UI 的情况下将 JSON 数据发布到 FastAPI?的详细内容。更多信息请关注PHP中文网其他相关文章!

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