How to Post JSON Data to FastAPI Without Swagger UI?

Patricia Arquette
Release: 2024-10-24 05:26:02
Original
778 people have browsed it

How to Post JSON Data to FastAPI Without Swagger UI?

Posting JSON Data to FastAPI Without Swagger UI

When working with FastAPI, it's useful to understand how to post JSON data to its backend without relying on Swagger UI. This approach allows for direct posting of data through a specified URL and retrieval of results in the browser.

Using a Javascript Interface

To achieve this, you can implement a Javascript interface such as Fetch API, which enables the submission of data in JSON format. Consider the following code example:

<code class="javascript">body: JSON.stringify({name: "foo", roll: 1})</code>
Copy after login

This code snippet converts the Javascript object into JSON for transmission.

Frontend Implementation

To interact with the FastAPI backend, you can leverage either of the following methods:

  • Jinja2Templates: This technique involves rendering an HTML/JS template that includes a form for submitting data. The form-data can then be converted into JSON.
  • Direct JSON Posting: Using Fetch API, you can directly post JSON data without involving a form.

Example Implementation

Consider the following example implementation in Python:

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

templates/index.html

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

By following these steps, you can effectively post JSON data to a FastAPI backend without the need for Swagger UI. This approach allows for greater flexibility and direct interaction with the backend through the specified URL.

The above is the detailed content of How to Post 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!