python requests content type

Python Requests Content Type

When sending HTTP requests using Python's requests library, it's important to specify the Content-Type header in the request. This header tells the server what type of content is being sent in the request body. The requests library provides a simple way to set this header.

Setting Content-Type Header

To set the Content-Type header in a requests request, you can use the headers parameter. For example:


import requests

url = 'https://example.com/api'
data = {'key': 'value'}
headers = {'Content-Type': 'application/json'}

response = requests.post(url, json=data, headers=headers)

In this example, we are sending a POST request to https://example.com/api with the JSON data {'key': 'value'}. We have also set the Content-Type header to application/json, which tells the server that we are sending JSON data.

Common Content Types

Here are some common Content-Type headers:

  • application/json: JSON data
  • application/x-www-form-urlencoded: URL-encoded form data
  • multipart/form-data: Form data that includes file uploads
  • text/plain: Plain text data
  • text/html: HTML data

You should always set the Content-Type header to the appropriate type for the data you are sending.