python requests post example with headers

Python Requests POST Example with Headers

When working with APIs, sometimes you need to send a POST request to the server. In Python, the requests library is a popular choice for making HTTP requests. In this example, we will send a POST request with custom headers using requests.

Step 1: Import the requests Library

The first step is to import the requests library. You can do this by adding the following line at the top of your Python file:


import requests

Step 2: Define the Headers and Payload

Next, we need to define the headers and payload for the POST request. Headers are key-value pairs that provide additional information about the request, such as the content type or authentication credentials. Payload is the data that will be sent with the POST request. For this example, we will send a JSON payload.


headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
}

payload = {
    'key1': 'value1',
    'key2': 'value2'
}

Note that you will need to replace YOUR_ACCESS_TOKEN with your actual access token.

Step 3: Send the POST Request

Now we can send the POST request using the requests.post() method. We need to pass in the URL, headers, and payload as arguments.


url = 'https://api.example.com/endpoint'

response = requests.post(url, headers=headers, json=payload)

The json parameter is used to automatically serialize the payload to JSON.

Step 4: Handle the Response

Finally, we need to handle the response from the server. We can access the response status code, headers, and content using properties of the response object.


status_code = response.status_code
response_headers = response.headers
response_content = response.content

You can also use the response.json() method to deserialize the response content from JSON to a Python object.

That's it! You now know how to send a POST request with custom headers using requests.