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:
以上是從 JavaScript 發送 JSON 資料到 FastAPI 如何處理錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!