How to Send JSON Data to FastAPI Endpoints without Swagger UI?

Patricia Arquette
Release: 2024-10-24 02:32:02
Original
456 people have browsed it

How to Send JSON Data to FastAPI Endpoints without Swagger UI?

Bypassing Swagger UI for JSON Data Posting in FastAPI

While the Swagger UI (OpenAPI) offers a convenient way to test API endpoints, there may be scenarios where you need to send JSON data directly without its use. This article provides a solution for posting JSON data to a FastAPI endpoint using a JavaScript interface.

To achieve this, we will utilize the Fetch API, which allows for sending data in JSON format. Additionally, we will employ Jinja2Templates to create a template for the frontend.

Backend Implementation

In app.py, the FastAPI application is defined with a / endpoint that accepts POST requests with a Item model.

<code class="python">from fastapi import FastAPI, Request, HTTPException
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    roll: int

app = FastAPI()
templates = Jinja2Templates(directory="templates")

@app.post("/")
async def create_item(item: Item):
    if item.name == "bad request":
        raise HTTPException(status_code=400, detail="Bad request.")
    return item

@app.get("/")
async def index(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})</code>
Copy after login

Frontend Implementation

In the index.html template, an HTML form is provided for inputting name and roll data. The submitForm() function uses the Fetch API to send the data as JSON.

<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())
        .then(data => {
          document.getElementById("responseArea").innerHTML = data;
        })
        .catch(error => {
          console.error(error);
        });
      }
    </script>
  </body>
</html></code>
Copy after login

Usage

Navigate to http://localhost:8080/ to access the frontend. Input data into the form and click the "Submit" button. The response from the / endpoint will be displayed in the "responseArea" div of the HTML.

Note that you can handle exceptions thrown by the endpoint in your JavaScript code by using the .catch() method, as shown in the example.

The above is the detailed content of How to Send JSON Data to FastAPI Endpoints 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!