Course contentsShow
← Python
Lesson 816 of 1,06013. Data Integration and Web APIsFree lesson

Managing Complex Request Headers for Content Negotiation

Learners will be able to configure specific Accept and Content-Type headers to request and process diverse data formats from professional API endpoints.

In this lesson, you will learn how to use Accept and Content-Type headers to communicate precisely which data formats your application is prepared to send and receive when interacting with professional APIs.

The Role of Content Negotiation

Content negotiation is the mechanism where the client and server agree on the "language" of the data being exchanged. While a simple API might default to JSON, professional services often support multiple formats like XML, YAML, or binary formats like Protocol Buffers.

The Accept header tells the server what your Python client prefers, while the Content-Type header informs the server about the format of the data you are currently sending in your request body.

Implementing Negotiation with requests

When working with the requests library, you define these preferences within the headers dictionary. By providing a quality value (q-value), you can even signal a hierarchy of preferences to the server.

import requests

# Define headers to negotiate content
headers = {
    'Accept': 'application/json;q=0.9, application/xml;q=0.8',
    'Content-Type': 'application/json'
}

data = {"user_id": 123, "action": "update"}

# Sending the request with specified content negotiation
response = requests.post(
    'https://api.example.com/data', 
    json=data, 
    headers=headers
)

# Verify what the server returned
print(f"Received content type: {response.headers.get('Content-Type')}")

In this example, the Accept header uses q=0.9 for JSON and q=0.8 for XML. This tells the server: "I prefer JSON, but if you don't have it, XML is an acceptable fallback." If the server supports both, it will select JSON based on your higher weight.

Always check the Content-Type returned in the response headers. If a server ignores your Accept header and returns a format you didn't request, attempting to parse it as JSON will trigger errors. By explicitly setting these headers, you ensure your integration logic remains robust, even when communicating with services that host multiple data representations on the same endpoint.

Key Takeaway: Use the Accept header to negotiate your preferred response format and the Content-Type header to explicitly declare the format of your sent payload.