Home > Backend Development > Python Tutorial > How to Send JSON Data from a JavaScript Front-End to a FastAPI Back-End?

How to Send JSON Data from a JavaScript Front-End to a FastAPI Back-End?

DDD
Release: 2024-11-10 14:05:03
Original
447 people have browsed it

How to Send JSON Data from a JavaScript Front-End to a FastAPI Back-End?

Sending JSON Data from JavaScript Front-End to FastAPI Back-End

In FastAPI, parameters declared in a function without being part of path parameters are automatically interpreted as query parameters. This interpretation differs from the common practice of passing JSON data in a request body.

To address this discrepancy, there are several options:

Using Pydantic Model

Create a Pydantic model to define the expected JSON body:

from pydantic import BaseModel

class Item(BaseModel):
    eth_addr: str

@app.post("/ethAddress")
def add_eth_addr(item: Item):
    return item
Copy after login

JavaScript Fetch API:

headers: {
  Accept: "application/json",
  "Content-Type": "application/json",
},
body: JSON.stringify({ eth_addr: "some addr" }),
Copy after login
Copy after login

Using Body Parameter

Use Body= with a type:

from fastapi import Body

@app.post("/ethAddress")
def add_eth_addr(eth_addr: str = Body()):
    return {"eth_addr": eth_addr}
Copy after login

JavaScript Fetch API:

headers: {
  Accept: "application/json",
  "Content-Type": "application/json",
},
body: JSON.stringify("some addr"),
Copy after login

Using Body Embed Parameter

Simplify body-only parameters using embed=True:

@app.post("/ethAddress")
def add_eth_addr(eth_addr: str = Body(embed=True)):
    return {"eth_addr": eth_addr}
Copy after login

JavaScript Fetch API:

headers: {
  Accept: "application/json",
  "Content-Type": "application/json",
},
body: JSON.stringify({ eth_addr: "some addr" }),
Copy after login
Copy after login

For additional details and examples with JavaScript, refer to:

  • https://fastapi.tiangolo.com/advanced/requestBody/
  • https://fastapi.tiangolo.com/tutorial/body-forms/#formencoded-or-raw-body-few-parameters
  • https://stackoverflow.com/questions/55333220/fastapi-validation-for-payload-when-using-body

Remember, using query parameters is not the typical approach for JSON body data in web APIs. Adjust your code accordingly to match these options.

The above is the detailed content of How to Send JSON Data from a JavaScript Front-End to a FastAPI Back-End?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template