python requests module content type

Python Requests Module Content Type

If you are working with Python and need to retrieve data from the web, the Requests Module is a must-have. It allows you to send HTTP/1.1 requests to any URL and then parse the response. One of the most important aspects of this module is the Content-Type header. The Content-Type header tells you what type of data you are receiving, so you can process it accordingly.

Retrieving Content-Type with Requests Module

To retrieve the Content-Type header with the Requests Module, you can use the .headers attribute of the response object. The .headers attribute is a dictionary that maps the header names to their values. To retrieve the Content-Type header specifically, you can use .headers['Content-Type'].


import requests

response = requests.get('http://www.example.com')
content_type = response.headers['Content-Type']

print(content_type)
    

Setting Content-Type with Requests Module

You can also set the Content-Type header when sending a request with the Requests Module. To do this, you use the headers parameter and set the value of the Content-Type header to the appropriate MIME type. For example:


import requests

headers = {'Content-Type': 'application/json'}
data = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://www.example.com/api', headers=headers, json=data)

print(response.text)
    

In the above example, we are sending a JSON payload, so we set the Content-Type header to application/json. If you were sending a different type of data, you would use a different MIME type.

Conclusion

The Content-Type header is an important part of working with web data in Python. With the Requests Module, you can easily retrieve and set this header to ensure that you are working with the correct data type. Remember to always specify the correct MIME type for your data to ensure that it is processed correctly.