How to Submit JSON Data to FastAPI without Swagger UI?

Susan Sarandon
Release: 2024-10-24 02:25:29
Original
856 people have browsed it

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:

<code class="javascript">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
});</code>
Copy after login

HTML Form and Jinja2 Templates

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

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>
Copy after login

index.html

<code class="html"><form method="post">
    <input type="text" name="name" value="foo">
    <input type="number" name="roll" value="1">
    <input type="submit" value="Submit">
</form>

<div id="responseArea"></div>

<script>
    document.querySelector('form').addEventListener('submit', (event) => {
        event.preventDefault();
        var data = new FormData(event.target);

        fetch('/', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(Object.fromEntries(data))
        }).then(resp => {
            return resp.text();
        }).then(data => {
            document.getElementById("responseArea").innerHTML = data;
        }).catch(error => {
            console.error(error);
        });
    });
</script></code>
Copy after login

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

The above is the detailed content of How to Submit JSON Data to FastAPI without Swagger UI?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!