How to Resolve FastAPI's 422 Error When Sending JSON Data via POST Requests
The 422 Unprocessable Entity error typically occurs when a request's payload is syntactically correct, but it doesn't match the server's expectations. In this specific case, you're encountering this error because your request is trying to send JSON data to an endpoint that anticipates receiving data as query parameters.
To resolve this issue, there are multiple approaches available:
Option 1: Utilize Pydantic Models
from pydantic import BaseModel class User(BaseModel): user: str @app.post('/') def main(user: User): return user
Option 2: Employ Body Parameters
from fastapi import Body @app.post('/') def main(user: str = Body(..., embed=True)): return {'user': user}
Option 3: Utilize Dict Type
from typing import Dict, Any @app.post('/') def main(payload: Dict[Any, Any]): return payload
Option 4: Directly Access Request Body
from fastapi import Request @app.post('/') async def main(request: Request): return await request.json()
Testing the 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())
Using JavaScript's Fetch API:
fetch('/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({'user': 'foo'}) }).then(resp => resp.json()) .then(data => { console.log(data); }) .catch(error => { console.error(error); });
By selecting and implementing one of these approaches, you can successfully handle JSON data in your FastAPI endpoint, resolving the 422 error.
The above is the detailed content of How to Fix FastAPI's 422 Error When POSTing JSON Data?. For more information, please follow other related articles on the PHP Chinese website!