如何在没有 Swagger UI 的情况下将 JSON 数据发布到 FastAPI?
在没有 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中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Linux终端中查看Python版本时遇到权限问题的解决方法当你在Linux终端中尝试查看Python的版本时,输入python...

使用FiddlerEverywhere进行中间人读取时如何避免被检测到当你使用FiddlerEverywhere...

在使用Python的pandas库时,如何在两个结构不同的DataFrame之间进行整列复制是一个常见的问题。假设我们有两个Dat...

如何在10小时内教计算机小白编程基础?如果你只有10个小时来教计算机小白一些编程知识,你会选择教些什么�...

Uvicorn是如何持续监听HTTP请求的?Uvicorn是一个基于ASGI的轻量级Web服务器,其核心功能之一便是监听HTTP请求并进�...

攻克Investing.com的反爬虫策略许多人尝试爬取Investing.com(https://cn.investing.com/news/latest-news)的新闻数据时,常常�...
