Skip to content

Python requests: POST Request Explained

Python requests - Post Request Tutorial Cover Image

In this tutorial, you’ll learn how to use the Python requests library’s POST function to post data via HTTP. The Python requests library abstracts the complexities in making HTTP requests. The requests.post() function allows you to post data to a web resource.

By the end of this tutorial, you’ll have learned:

Understanding the Python requests POST Function

An HTTP POST request is used to send data to a server, where data are shared via the body of a request. In the request.post() function, data are sent with the data parameter, which accepts a dictionary, a list of tuples, bytes or a file object.

Let’s take a look at what the requests.post() function looks like in Python:

# Understanding the requests.post() Function
import requests

requests.post(
   url, 
   data=None,
   json=None,
   **kwargs
)

We can see that the function accepts three parameters:

  1. url, which defines the URL to post to
  2. data, which accepts a dictionary, list of tuples, butes, or a file-like object to send in the body of the request
  3. json, which represents json data to send in the body of the request

Additionally, the function accept a number of different keyword arguments inherited from the requests.request() function. These keyword arguments can be passed in directly and are described in the table below:

ParameterDescriptionDefault Value
allow_redirectsWhether or not to allow redirectionTrue
authA tuple to enable secure HTTP authenticationNone
certA string or tuple specifying the certification file or keyNone
cookiesA dictionary of cookies to send to the specified URLNone
headersA dictionary of HTTP headers to sendNone
proxiesA dictionary of the protocol of the proxy URLNone
streamA boolean indicator to determine if the response should be downloaded (when set to False) or streamed (when set to True)False
timeoutA number or tuple indicating how many seconds to wait for a client to make a connection or send a response. The default value of None means that the request will wait indefinitely. None
verifyA boolean or string indication to test the server’s TLS certificateTrue
The optional keyword arguments available in the requests.post() function

In the following section, you’ll learn how to make a POST request using the request.post() function.

Making a Python requests POST Request

In this section, you’ll learn how to make an HTTP POST request using the post() function from the requests library. To illustrate this, we’ll be using the https://httpbin.org/ website, which allows us to place actual POST requests.

Let’s create our first POST request using Python:

# Creating a POST Request with requests.post
import requests
resp = requests.post('https://httpbin.org/post')
print(resp)

# Returns:
# <Response [200]>

In the example above, we simply pass the URL to the /post endpoint into the requests.post() function. We then print the response that we get back, which returns a Response object.

We can pass data into the request by using the data= parameter. Let’s pass in a dictionary of data and see what is returned:

# Passing Data into Our POST Request
import requests
resp = requests.post('https://httpbin.org/post', data={'website': 'datagy.io'})
print(resp)

# Returns:
# <Response [200]>

In the following section, you’ll learn how to understand how these Response objects work.

Understanding the Python requests response Object

In the previous section, you learned how to create your first HTTP POST request, which returned a Response object. This object provides a lot of useful information that helps you understand the context of the request and response.

We can see whether or not the request was made successfully by inspecting either the .status_code property or the .ok property:

# Inspecting the Status of the Request
import requests
resp = requests.post('https://httpbin.org/post', data={'website': 'datagy.io'})
print(resp.ok)
print(resp.status_code)

# Returns:
# True
# 200

By analyzing the code above, we can see that the request was made successfully.

Let’s now take a look at what the request returns, by analyzing the .text property:

# Analyzing the Text of the Request
import requests
resp = requests.post('https://httpbin.org/post', data={'website': 'datagy.io'})
print(resp.text)

# Returns:
# {
#   "args": {}, 
#   "data": "", 
#   "files": {}, 
#   "form": {
#     "website": "datagy.io"
#   }, 
#   "headers": {
#     "Accept": "*/*", 
#     "Accept-Encoding": "gzip, deflate, br", 
#     "Content-Length": "17", 
#     "Content-Type": "application/x-www-form-urlencoded", 
#     "Host": "httpbin.org", 
#     "User-Agent": "python-requests/2.27.1", 
#     "X-Amzn-Trace-Id": ""
#   }, 
#   "json": null, 
#   "origin": "", 
#   "url": "https://httpbin.org/post"
# }

From this, we can see that request was passed in as a 'form' type. It may not always be ideal to pass data in as a form type. Because of this, you can specify the type of data passed in via the request.post() function headers.

Passing Headers into a Python requests POST Function

The headers= parameter in the requests.post() function allows you to specify the type of data being passed in. For example, we can specify the content-type of the data. Let’s see how we can pass a JSON-formatted string into our function and specify the content type:

# Specifying the Content Type of a POST Request
import requests
import json
resp = requests.post(
    'https://httpbin.org/post', 
    data=json.dumps({'website': 'datagy.io'}),
    headers={"Content-Type": "application/json"})

print(resp)

# Returns: <Response [200]>

Let’s break down what we did above:

  1. We passed in a JSON-formatted string into the data= parameter
  2. We passed in headers that directly the request to pass in JSON data a

When working with JSON-data, this can feel a little complex. Because of how often you’ll pass JSON data into the request, the requests library has a simple way of handling this.

Sending JSON Data with Python requests

Because of how often you may want to pass in JSON data into a POST request, Python handles this quite easily. Rather than passing data into the data=, you can pass JSON data directly into the json= parameter. This handles configuring the rest of the function to encode the data appropriately.

Let’s see how we can post JSON data using the requests.post() function:

# Sending JSON Data with the json.post() Function
import requests
import json
resp = requests.post(
    'https://httpbin.org/post', 
    json={'website': 'datagy.io'},
)

print(resp)

# Returns: <Response [200]>

In the function call above, we passed a dictionary into the json= parameter, which allowed the function to convert it into a JSON object.

Conclusion

In this tutorial, you learned how to use the Python requests library to send a POST request via the post() function. You first learned what a POST request is and how the post() function works. Then, you learned how to create your first POST request using the httpbin.org website. Then, you learned how to customize your POST request by passing in data, headers, and JSON-formatted data.

Additional Resources

To learn more about related topics, check out the tutorials below:

Nik Piepenbreier

Nik is the author of datagy.io and has over a decade of experience working with data analytics, data science, and Python. He specializes in teaching developers how to use Python for data science using hands-on tutorials.View Author posts

1 thought on “Python requests: POST Request Explained”

  1. my account had suspension into last weak in 18.12.2022 objective is share another so face book ban in 30 days.now i want to my face book accound.please help me.thank a lot

Leave a Reply

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