Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading