我正在尝试使用 FastAPI 执行简单的 POST
操作。我使用 BaseModel
创建了一个基本结构,它只有两个属性,即 name
和 roll
。
import uvicorn
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
name: str
roll: int
app = FastAPI()
@app.post("/")
async def create_item(item: Item):
return item
if __name__ == '__main__':
uvicorn.run(app, port=8080, host='0.0.0.0')
我想使用此 POST
操作发布这些数据 -
{“名称”:“XYZ”,“卷”:51}
。
我知道 Swagger UI (OpenAPI) 提供的 http://localhost:8080/docs
自动文档,我们可以用它来发布数据。但我不想使用它。我想要的是使用 URL http://localhost:8080/
直接发布数据,并希望在浏览器本身中查看结果,而不是在 Swaggger UI 中查看结果。
最佳答案
您需要使用 Javascript 接口(interface)/库,例如 Fetch API ,它允许您以 JSON
格式发送数据(示例如下)。提交Form
相反,请查看 this answer ,而要发布 Files
和 Form
/JSON
数据,请查看 this answer .
对于前端,您可以使用 Jinja2Templates
渲染并返回包含您的 HTML
/JS
代码等的 TemplateResponse
。您可以使用 HTML form
提交您的数据,然后将 form-data
转换为 JSON
,如所述 here 。否则,您可以直接发布您的 JSON
数据,如下所示 here —例如,body: JSON.stringify({name: "foo", roll: 1})
。
app.py
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})
模板/index.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>
关于python - 如何在不使用 Swagger UI 的情况下将 JSON 数据发布到 FastAPI 后端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71740992/