Setting the Content-Type Header for Python Requests

Feb 3, 2024 ยท 2 min read

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 Content-Type used by Requests is application/x-www-form-urlencoded. This is suitable for basic form data being sent in simple key-value pairs. However, when sending JSON data or other formats, you'll want to explicitly set the header instead.

Setting Content-Type for JSON

When sending JSON data in a request body, you should set the Content-Type to application/json. This tells the server to interpret the request body as JSON:

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:

  • Import the json module to serialize the Python dict to JSON
  • Set headers to include 'Content-Type': 'application/json'
  • Use json.dumps() on the data to convert to JSON string
  • 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 2xx status code to confirm success. You can also check that the Content-Type header of the response matches what you expect from the server.

    Handling content types appropriately is important for robust integrations. Setting the headers explicitly gives you more control over requests in Python.

    Browse by tags:

    Browse by language:

    The easiest way to do Web Scraping

    Get HTML from any page with a simple API call. We handle proxy rotation, browser identities, automatic retries, CAPTCHAs, JavaScript rendering, etc automatically for you


    Try ProxiesAPI for free

    curl "http://api.proxiesapi.com/?key=API_KEY&url=https://example.com"

    <!doctype html>
    <html>
    <head>
        <title>Example Domain</title>
        <meta charset="utf-8" />
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
    ...

    X

    Don't leave just yet!

    Enter your email below to claim your free API key: