post json data in python requests

How to POST JSON Data in Python Requests

Python is a often used to build high traffic websites and applications. While doing so, web developers may need to send POST JSON data in python requests. In this article, we have learnt how to POST JSON Data in Python requests.


How to POST JSON Data in Python Requests

You can easily send and accept requests in Python using requests library. It provides a function post() that allows you to include POST data in different formats. Let us say you want to send JSON Data to https://example.com/post from a python client to a web server.

Here is the code snippet to POST JSON Data in Python requests. You need to use this code in client side that is sending request to the server and displaying the status code of response returned by the server.

>>> import requests
>>> r = requests.post('https://example.com/post', json={"key": "value"})
>>> r.status_code
200

You can check out the request payload using the following command.

>>> r.json()

Alternatively, you can also use json.dumps() to send data in JSON form. It basically converts python dictionary (and other objects) into their equivalent JSON format.

import requests

url = "https://example.com/post"
data = {'key':'value'}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json.dumps(data), headers=headers)

In this article, we have learnt how to POST JSON Data in Python.

Also read:

How to Remove SSL Certificate & SSH Passphrase in Linux
How to Capture Linux Signal in Python
How to Send Signal from Python
How to Clear Canvas for Redrawing in JS
How to Use Decimal Step for Range in Python

Leave a Reply

Your email address will not be published.