通过使用这些技术,您可以方便地将 JSON 数据发布到 FastAPI 后端,而无需依赖 Swagger UI 界面。
","image":"http://www.luping.net/uploads/20241025/1729834590671b2e5e700bb.jpg","datePublished":"2024-11-07T00:35:56+08:00","dateModified":"2024-11-07T00:35:56+08:00","author":{"@type":"Person","name":"luping.net","url":"https://www.luping.net/articlelist/0_1.html"}}使用 FastAPI 时,可以在没有 Swagger UI 中介的情况下发布 JSON 数据。实现此目的的方法如下:
采用基于 JavaScript 的接口(例如 Fetch API)以 JSON 格式发送数据。这是一个例子:
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
});
或者,您可以使用 Jinja2 模板和 HTML 表单来提交数据。方法如下:
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})
通过使用这些技术,您可以方便地将 JSON 数据发布到 FastAPI 后端,而无需依赖 Swagger UI 界面。
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3