By using these techniques, you can conveniently post JSON data to your FastAPI backend without relying on the Swagger UI interface.
","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"}}When working with FastAPI, it's possible to post JSON data without the intermediary of the Swagger UI. Here's how to achieve this:
Employ a JavaScript-based interface like the Fetch API to send data in JSON format. Here's an example:
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
});
Alternatively, you can utilize Jinja2 Templates and an HTML form to submit your data. Here's how:
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})
By using these techniques, you can conveniently post JSON data to your FastAPI backend without relying on the Swagger UI interface.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3