1

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

Gabriel Knies
  • 129
  • 1
  • 1
  • 8

1 Answers1

3

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.

Elias Dorneles
  • 22,556
  • 11
  • 85
  • 107