How to post JSON data to FastAPI backend without using Swagger UI?
Asked Answered
R

1

2

I am trying to do a simple POST operation using FastAPI. I have created a basic structure using BaseModel, which has only two attributes, namely name and 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')

I would like to post these data using this POST operation - {"name":"XYZ", "roll":51}.

I know about the automatic documentation at http://localhost:8080/docs provided by Swagger UI (OpenAPI), which we can use to post data. But I wouldn't want to use it. What I would like is to directly post the data using the URL http://localhost:8080/ and would like to see the result in the browser itself, instead of seeing the result in Swaggger UI.

Rafat answered 4/4, 2022 at 16:58 Comment(0)
D
4

You would need to use a Javascript interface/library such as Fetch API, which allows you to send data in JSON format (example is given below). For submiting Form data instead, have a look at this answer, while for posting both Files and Form/JSON data, have a look at this answer.

For the frontend, you could use Jinja2Templates to render and return a TemplateResponse that includes your HTML/JS code, etc. You can use an HTML form to submit your data and then have the form-data converted into JSON, as described here. Otherwise, you could post your JSON data directly, as shown here—for example, 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})

templates/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>
Dmitri answered 4/4, 2022 at 17:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.