Last Updated On
In this tutorial, we will add header to the Python Request.
Prerequisite:
- Python is installed on the machine
- PIP is installed on the machine
- PyCharm or other Python Editor is installed on the machine
If you need help in installing Python, please refer to this tutorial – How to Install Python on Windows 11.
If you need help in installing PyCharms, please refer to this tutorial – How to install PyCharms on Windows 11.
What are HTTP headers?
HTTP headers let the client and the server pass additional information with an HTTP request or response. All the headers are case-insensitive, headers fields are separated by colon, key-value pairs in clear-text string format.
Headers = { “Authorization” : ”our_unique_secret_token” }
Below is the example of POST Request with header.
![](https://qaautomation.expert/wp-content/uploads/2023/12/image-193.png?w=1200)
Installation of Python Requests Module
Step 1 – If you are using PyCharm IDE then you need to install the Request library. Execute the below command using pip.
pip install -U requests
Step 2 – Install Pytest
pip install -U pytest
Step 3 – Create a new project folder and open it in PyCharm.
![](https://qaautomation.expert/wp-content/uploads/2023/12/image-171.png?w=334)
Step 4 – Go to the project folder and Create a new file, name it “PostRequest.py”.
![](https://qaautomation.expert/wp-content/uploads/2023/12/image-180.png?w=271)
Step 5 – Create the test
Import the required packages.
The POST method is used to get the resource from the server and returns 201 for successful call.
import requests
ENDPOINT = 'https://reqres.in/api/users'
def test_add_header():
request_body = {
"name": "Vibha",
"Job": "CEO"
}
header = {"Content-Type": "application/json; charset=utf-8"}
response = requests.post(ENDPOINT, request_body, header)
print(response.json())
print("Request Header", response.request.headers)
print("Response Header", response.headers)
assert response.status_code == 201
assert response.headers["Content-Type"] == "application/json; charset=utf-8"
requests.post(url, data=data, header=header) – function sends a POST request to the specified URL with the provided data. The data dictionary contains the key-value pairs that we want to send in the POST request payload. You can modify it based on the requirements of the API we are working with. The header dictionary also contains the key-value pair.
The response object contains information about the response, including the status code and the response content.
We can assert the header of the response also as shown below:
assert response.headers["Content-Type"] == "application/json; charset=utf-8"
Step 6 – To run the test through command line, use the below command:
pytest PostRequest_test.py -s
The output of the above program is
![](https://qaautomation.expert/wp-content/uploads/2024/01/image-145.png?w=1200)
That’s it! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!