Home  >  Article  >  Backend Development  >  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
DDDOriginal
2024-11-10 14:05:03423browse

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

JavaScript Fetch API:

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

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}

JavaScript Fetch API:

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

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}

JavaScript Fetch API:

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

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!

Statement:
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