0

I am using fastapi and when I send post with following code, it return below error:

{'detail': [{'loc': ['body'], 'msg': 'value is not a valid dict', 'type': 'type_error.dict'}]}

My code is :

import requests
import json
import datetime

def main():
    time = datetime.datetime.now().isoformat()

    transaction = {
        "time": time,
        "sender": "COCOCOCO",
        "receiver": "AAAAAA",
        "amount": AAA,
        "description": "Christmas Dinner Fee",
        "signature": "signature_sample"
    }

    url ="https://XXXXXX.deta.dev/transaction_pool/"
    res = requests.post(url, json.dumps(transaction))
    print(res.json())

if __name__ == "__main__":
    main()

How do I fix it?

Azhar Khan
  • 3,829
  • 11
  • 26
  • 32
king1982
  • 11
  • 1
  • Using a dict as a response model is really generic, I would advise to use a pydantic model for this. The error happens because you are sending a json as a string and it expects a dict. – Cloudkollektiv Jan 10 '23 at 10:43

1 Answers1

2

What you are sending in your POST request is not a valid dict object. It could be that you are converting the "transaction" dictionary to a JSON string with json.dumps before sending the request. This will cause the request to contain a JSON string instead of a Python dict object.

Instead of using json.dumps, you can use the json argument to directly send the dictionary in the request. This automatically converts the dictionary to a JSON string before sending it:

res = requests.post(url, json=transaction)

You can also send the dictionary converted to a json object using the json() method,

res = requests.post(url, data=json.dumps(transaction))