>  기사  >  백엔드 개발  >  Swagger UI 없이 FastAPI에 JSON 데이터를 게시하는 방법은 무엇입니까?

Swagger UI 없이 FastAPI에 JSON 데이터를 게시하는 방법은 무엇입니까?

Patricia Arquette
Patricia Arquette원래의
2024-10-24 05:26:02779검색

How to Post JSON Data to FastAPI Without Swagger UI?

Swagger UI 없이 FastAPI에 JSON 데이터 게시

FastAPI로 작업할 때 Swagger UI 없이 JSON 데이터를 백엔드에 게시하는 방법을 이해하면 유용합니다. Swagger UI에 의존합니다. 이 접근 방식을 사용하면 지정된 URL을 통해 데이터를 직접 게시하고 브라우저에서 결과를 검색할 수 있습니다.

Javascript 인터페이스 사용

이를 달성하려면 JSON 형식으로 데이터를 제출할 수 있는 Fetch API와 같은 Javascript 인터페이스입니다. 다음 코드 예를 살펴보세요.

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

이 코드 조각은 전송을 위해 Javascript 개체를 JSON으로 변환합니다.

프런트엔드 구현

FastAPI 백엔드에서는 다음 방법 중 하나를 활용할 수 있습니다.

  • Jinja2Templates: 이 기술에는 데이터 제출을 위한 양식이 포함된 HTML/JS 템플릿을 렌더링하는 작업이 포함됩니다. 그런 다음 양식 데이터를 JSON으로 변환할 수 있습니다.
  • JSON 직접 게시: Fetch API를 사용하면 양식을 사용하지 않고도 JSON 데이터를 직접 게시할 수 있습니다.

구현 예

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>

template/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>

이 단계를 따르면 Swagger UI 없이도 JSON 데이터를 FastAPI 백엔드에 효과적으로 게시할 수 있습니다. 이 접근 방식을 사용하면 지정된 URL을 통해 더 큰 유연성과 백엔드와의 직접적인 상호 작용이 가능합니다.

위 내용은 Swagger UI 없이 FastAPI에 JSON 데이터를 게시하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.