HTTP headers are key-value pairs that allow you to pass additional information in a request. For example, headers can specify information such as the MIME type, user authentication tokens, and etc.
In this article, we will learn how to pass the Content-Type header in a Post request using the Python requests library.
What is a Content-Type Header?
The Content-Type header allows you to specify the media type of a given resource. This overwrites any prior content type encoding. Keep in mind that browsers may ignore the Content-Type header when other parameters are set.
You can learn more about the Content-Type Header information in the resource below:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
Example
The following code shows an example of sending JSON data in a post request and setting the Content-Type header.
URL = 'https://google.com/'
headers = {'Content-Type': 'application/json; charset=utf-8'}
body = {
'username': 'linuxhint',
'password': 'pasword'
}
resp = requests.post(url=URL, headers=headers, json=body)
print(resp.json())
The above illustrates how to send JSON data using a POST request. We also demonstrate how to set the Content-Type value in the POST request.
Conclusion
In this short article, we discussed how to set the Content-Type header in a POST request using the request.post() function.