Categories
Python Answers

How to POST JSON data with Python Requests?

Spread the love

Sometimes, we want to POST JSON data with Python Requests.

In this article, we’ll look at how to POST JSON data with Python Requests.

How to POST JSON data with Python Requests?

To POST JSON data with Python Requests, we call the requests.post method.

For instance, we write:

import requests

r = requests.post('http://httpbin.org/post', json={"key": "value"})
print(r.status_code)
print(r.json())

We call requests.post with the URL to make request to and the json request payload.

The response object is the returned and assigned to r.

We get the status code from r.status_code and the response body from r.json.

r.status_code should be 200.

And r.json should return:

{'args': {}, 'data': '{"key": "value"}', 'files': {}, 'form': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '16', 'Content-Type': 'application/json', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.26.0', 'X-Amzn-Trace-Id': 'Root=1-616c8c56-6e89c2ab7addbeee5064302c'}, 'json': {'key': 'value'}, 'origin': '35.197.57.70', 'url': 'http://httpbin.org/post'}

Conclusion

To POST JSON data with Python Requests, we call the requests.post method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *