31

I'm writing wrapper for REST API and use requests module.

Method .json() of Response object transfers **kwargs to json.loads() function, so I can easily use custom JSON decoder and, i. e. transparently convert UNIX epoch timestamps to datetime.datetime objects.

Is there any way to use custom JSON encoder with Request object? Seems I can only use parameter json, but can't find how to use custom JSON encoder with it.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195

1 Answers1

46

Extracting the answer from the link provided by alecxe, using a custom encoder and the json parameter is not supported. It's recommended you just construct the post manually.

r = requests.post('http://foo.bar',
              data=json.dumps(some_data, cls=CustomJSONEncoder),
              headers={'Content-Type': 'application/json'})
Jesse
  • 805
  • 9
  • 11
  • 4
    Thanks! Also, small note, when using `json=...`, requests adds a `content-type` value of `application/json`, which some servers expect. When calling requests with your own-encoded JSON payload, you may have to add `headers={'content-type': 'application/json'}` (again, depending if the server you're interacting with cares about this or not) – Greg Sadetsky Jul 07 '21 at 19:19