Fast API - post any key value data

Viewed 128

I'm using Fast.API I need an API to allow users to post any data, key/value - I use this to allow users to add custom profile key/value fields to profile, where key is of type string and value is string, number, boolean.

how do I add such route?

I'm using this route, but is not working:

@route.post('/update_profile')
def update_profile(acsess_token, **kargs):
    # I need here to get a dictionary like this: { "name": "John", "nick_name": "Juju", "birth_year": 1999, "allow_newsletter": False, }
    # and so on.... any key/value pair
    pass

I want to be able to post to this route any pair(s) key/value. Is any way to do it with FastAPI?

Thank you.

2 Answers

you can use the request object directly

from fastapi import FastAPI
from fastapi import Request

@app.post("/something")
async def get_body(request: Request):
    return await request.json()

After searching for a way to do it, I found this solution:

@route.post('/update_profile')
def update_profile(acsess_token, custom_fields: Optional[dict[str, Any]]):
   pass

And this is the best solution so far (for me).

Related