Home > Article > Backend Development > How to Handle Errors When Sending JSON Data from JavaScript to FastAPI?
Error Handling in Posting JSON Data from JavaScript to FastAPI
To send data from a JavaScript frontend to a FastAPI backend, you must ensure the data is passed in the correct format and to the appropriate endpoint. If you encounter a 422 Unprocessable Entity error, it's likely due to incorrect data formatting.
By default, FastAPI interprets function parameters not included in the path as query parameters. However, for JSON data, you need to specify it explicitly using one of the following methods:
Define a Pydantic model to represent the JSON data structure:
from pydantic import BaseModel class Item(BaseModel): eth_addr: str @app.post('/ethAddress') def add_eth_addr(item: Item): return item
Use the Body type to specify that the parameter should be parsed from the request body:
from fastapi import Body @app.post('/ethAddress') def add_eth_addr(eth_addr: str = Body()): return {'eth_addr': eth_addr}
For a single body parameter, you can use the embed=True argument to automatically parse the data from the request body:
from fastapi import Body @app.post('/ethAddress') def add_eth_addr(eth_addr: str = Body(embed=True)): return {'eth_addr': eth_addr}
When using the Fetch API in JavaScript to send JSON data, you must set the Content-Type header to application/json and specify the data in the body field:
fetch("http://localhost:8000/ethAddress", { method: "POST", headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ "eth_addr": "some address" }), });
For more information and detailed examples, refer to the following documentation and resources:
The above is the detailed content of How to Handle Errors When Sending JSON Data from JavaScript to FastAPI?. For more information, please follow other related articles on the PHP Chinese website!