Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom JSONEncoder for requests.post

Tags:

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.

like image 249
Valery Ryaboshapko Avatar asked Dec 19 '15 01:12

Valery Ryaboshapko


People also ask

What is the content type of a JSON request?

In this example, we are passing JSON, so the request’s content type is application/json. By specifying correct request headers so that the requests module can serialize your data into the correct Content-Type header format. In this can we don’t need to use the json parameter.

How do I add JSON data to a POST request?

Select POST request and enter your service POST operation URL. Click on Headers. In the key column enter Content-Type and in the Value column enter application/json. Click on the body section and click the raw radio button. enter your JSON data.

How do I test a postman request in JSON?

Test Your JSON POST request using postman before executing It is always a best practice to test your request along with its message body using postman to verify JSON data, and a request is in the required format. Let’s see how to test POST request using postman. Add Postman extension or install a native postman app.

Why do we need to specify correct request headers in JSON?

By specifying correct request headers so that the requests module can serialize your data into the correct Content-Type header format. In this can we don’t need to use the json parameter.


1 Answers

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'}) 
like image 58
Jesse Avatar answered Oct 25 '22 03:10

Jesse