When sending HTTP requests with the Python Requests library, you can specify headers like Content-Type to indicate the media type of data you are sending to the server. Properly setting the Content-Type helps the receiving server interpret and handle the data correctly.
The default
Setting Content-Type for JSON
When sending JSON data in a request body, you should set the
import requests
import json
data = {'key1': 'value1', 'key2': 'value2'}
headers = {'Content-Type': 'application/json'}
response = requests.post(url, headers=headers, data=json.dumps(data))
The key points here:
Uploading Multipart Form Data
When uploading files, you can use multipart form data encoding and should set the content type accordingly:
files = {'file': open('report.pdf', 'rb')}
headers = {'Content-Type': 'multipart/form-data'}
response = requests.post(url, headers=headers, files=files)
This allows sending files and data together in the same request while correctly indicating the media format being used.
Handling Responses
Once you have made the request, be sure to check that you get back a
Handling content types appropriately is important for robust integrations. Setting the headers explicitly gives you more control over requests in Python.