Home > Article > Backend Development > How to Send JSON Data from a JavaScript Front-End to a 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:
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" }),
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"),
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:
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!