Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

955
Views
FASTAPI: Getting Error 422 : Unprocessable Entity when trying to pass a json object inside body

I haven't seen an answer for my question yet, so here it is.

I'm trying to pass a json object like : inside a body of a post request in fastapi so that i'll store it inside a database later or process it in any way

{
  "action_reaction": {
    "action": {
      "name": "test"
    },
    "reaction": {
      "name2": "test2"
    }
  }
}

enter image description here

Here's my code :

class AddActionModel(BaseModel):
    action_reaction: str = None

@router.post("/add_reaction")
async def add_action_reaction(addActionModel: AddActionModel, x_token: str = Header(None)):
    print(f'addActionModel: {addActionModel}')

    action_reactions = json.loads(addActionModel.action_reaction)
    action = action_reactions["action"]
    reaction = action_reactions["reaction"]
    return {"success": True}

The problem is I always get this response: enter image description here

Does anyone has an idea on how to do it ?

Thanks

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

The JSON you're sending is invalid.

Your code is expecting a JSON object containing a string-value, which you're decoding on the server-side.

To make your request work, you want to escape the quotes inside of the action_reaction, like this:

{
    "action_reaction": "{\"action\": {\"name\": \"test\"}, \"reaction\": {\"name2\": \"test2\"}}"
}

Alternative: implement a nested model for all the objects:

class Event(BaseModel):
    name: str

class ActionReaction(BaseModel):
   action: Event
   reaction: Event

class AddActionModel(BaseModel):
    action_reaction: ActionReaction = None

If you define it like this, then no need to json.loads on the backend side, as the whole object will be parsed by FastAPI + Pydantic.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!