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"}}
"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Submit JSON Data to FastAPI without Swagger UI?

How to Submit JSON Data to FastAPI without Swagger UI?

Published on 2024-11-07
Browse:531

How to Submit JSON Data to FastAPI without Swagger UI?

Bypassing Swagger UI for JSON Data Input in FastAPI

When working with FastAPI, it's possible to post JSON data without the intermediary of the Swagger UI. Here's how to achieve this:

JavaScript Interface for JSON Data Submission

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
});

HTML Form and Jinja2 Templates

Alternatively, you can utilize Jinja2 Templates and an HTML form to submit your data. Here's how:

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

By using these techniques, you can conveniently post JSON data to your FastAPI backend without relying on the Swagger UI interface.

Release Statement This article is reprinted at: 1729684541 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

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