首页  >  文章  >  后端开发  >  如何在没有 Swagger UI 的情况下向 FastAPI 提交 JSON 数据?

如何在没有 Swagger UI 的情况下向 FastAPI 提交 JSON 数据?

Susan Sarandon
Susan Sarandon原创
2024-10-24 02:25:29848浏览

How to Submit JSON Data to FastAPI without Swagger UI?

在 FastAPI 中绕过 Swagger UI 进行 JSON 数据输入

使用 FastAPI 时,可以在没有 Swagger UI 中介的情况下发布 JSON 数据。以下是实现此目的的方法:

用于 JSON 数据提交的 JavaScript 接口

使用基于 JavaScript 的接口(例如 Fetch API)以 JSON 格式发送数据。下面是一个示例:

<code class="javascript">var data = {
    name: "foo",
    roll: 1
}

fetch('/', {
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
}).then(resp => {
    return resp.text();
}).then(data => {
    // Handle the response
});</code>

HTML 表单和 Jinja2 模板

或者,您可以使用 Jinja2 模板和 HTML 表单来提交数据。具体方法如下:

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>

index.html

<code class="html"><form method="post">
    <input type="text" name="name" value="foo">
    <input type="number" name="roll" value="1">
    <input type="submit" value="Submit">
</form>

<div id="responseArea"></div>

<script>
    document.querySelector('form').addEventListener('submit', (event) => {
        event.preventDefault();
        var data = new FormData(event.target);

        fetch('/', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(Object.fromEntries(data))
        }).then(resp => {
            return resp.text();
        }).then(data => {
            document.getElementById("responseArea").innerHTML = data;
        }).catch(error => {
            console.error(error);
        });
    });
</script></code>

通过使用这些技术,您可以方便地将 JSON 数据发布到 FastAPI 后端,而无需依赖在 Swagger UI 界面上。

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

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