Python

Python Post Request Set Content-Type

When working with HTTP requests, you will encounter instances where you must pass additional information within a POST request. This is where HTTP headers come into play.

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.

import requests
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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list