
直接將 JSON 數(shù)據(jù)發(fā)布到 FastAPI 后端
問題陳述:
使用 FastAPI 時,用戶可能希望將 JSON 數(shù)據(jù)直接發(fā)布到后端,而不使用 Swagger UI 進(jìn)行文檔記錄。相反,他們的目標(biāo)是通過指定的 URL 提交數(shù)據(jù)并在瀏覽器中接收結(jié)果。
解決方案:
為了實現(xiàn)這一點,JavaScript 庫(例如 Fetch API)可以就業(yè)。這些工具可以發(fā)送 JSON 格式的數(shù)據(jù)。
對于前端渲染,Jinja2Templates 可用于返回包含 HTML 和 JavaScript 代碼的模板。也可以直接發(fā)布 JSON 數(shù)據(jù),如下面的代碼示例所示。
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 數(shù)據(jù)發(fā)布到 FastAPI 后端,而無需依賴 Swagger UI。數(shù)據(jù)可以通過前端的表單提交并由后端 API 處理。
以上是如何將 JSON 數(shù)據(jù)直接發(fā)布到 FastAPI 后端?的詳細(xì)內(nèi)容。更多信息請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!