When constructing RESTful APIs, it's common to encounter issues related to data exchange, particularly when POST requests are involved. One such issue is receiving a "422 Unprocessable Entity" error while attempting to send JSON data.
In the provided code example:
from fastapi import FastAPI app = FastAPI() @app.post("/") def main(user): return user
This code defines a POST endpoint that expects a JSON payload containing a "user" key. However, the error occurs when the HTTP client sends JSON data that doesn't match the expected format. To resolve this, there are several options:
Pydantic models provide a way to validate and deserialize JSON payloads according to predefined schemas:
from pydantic import BaseModel class User(BaseModel): user: str @app.post("/") def main(user: User): return user
Body parameters in FastAPI allow you to directly parse the JSON payload without defining a Pydantic model:
from fastapi import Body @app.post("/") def main(user: str = Body(..., embed=True)): return {'user': user}
While less recommended, you can use a Dict type to receive the JSON payload as a key-value pair:
from typing import Dict, Any @app.post("/") def main(payload: Dict[Any, Any]): return payload
If you're sure that the incoming data is valid JSON, you can use Starlette's Request object to parse it:
from fastapi import Request @app.post("/") async def main(request: Request): return await request.json()
You can test these options using:
Python requests library:
import requests url = 'http://127.0.0.1:8000/' payload = {'user': 'foo'} resp = requests.post(url=url, json=payload) print(resp.json())
JavaScript Fetch API:
fetch('/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({'user': 'foo'}) }) .then(resp => resp.json()) // or, resp.text(), etc .then(data => { console.log(data); // handle response data }) .catch(error => { console.error(error); });
By implementing one of these approaches, you can resolve the 422 error and successfully handle JSON data in your FastAPI POST endpoints.
The above is the detailed content of How to Handle FastAPI's 422 Error When Receiving JSON POST Requests?. For more information, please follow other related articles on the PHP Chinese website!