Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

How to read all HTTP headers in Python CGI script?

When working with Python CGI scripts, you often need to access HTTP headers sent by the client. Apache's mod_cgi automatically converts HTTP headers into environment variables with an HTTP_ prefix.

How Apache Handles HTTP Headers

Apache's mod_cgi sets environment variables for each HTTP request header received. The variables follow a specific pattern:

  • All header names get an HTTP_ prefix
  • Header names are converted to uppercase
  • Hyphens are replaced with underscores

For example, x-client-version: 1.2.3 becomes HTTP_X_CLIENT_VERSION.

Reading a Specific Header

To read a specific custom header, use os.environ with the converted header name ?

import os

# Reading a specific header
client_version = os.environ.get("HTTP_X_CLIENT_VERSION", "Not found")
print(f"Client version: {client_version}")

Reading All HTTP Headers

The following CGI script prints all HTTP headers and their values ?

#!/usr/bin/env python3

import os

print("Content-Type: text/html")
print("Cache-Control: no-cache")
print()

print("<html><body>")
print("<h1>HTTP Headers</h1>")

for headername, headervalue in os.environ.items():
    if headername.startswith("HTTP_"):
        print("<p><b>{0}</b> = {1}</p>".format(headername, headervalue))

print("</body></html>")

Common HTTP Headers

Here are some common HTTP headers and their environment variable names:

HTTP Header Environment Variable Description
User-Agent HTTP_USER_AGENT Browser/client information
Accept HTTP_ACCEPT Accepted content types
Authorization HTTP_AUTHORIZATION Authentication credentials
Content-Type HTTP_CONTENT_TYPE Request body content type

Error Handling

Always use os.environ.get() with a default value to handle missing headers gracefully ?

import os

# Safe way to read headers
user_agent = os.environ.get("HTTP_USER_AGENT", "Unknown")
auth_header = os.environ.get("HTTP_AUTHORIZATION", "")

print(f"User Agent: {user_agent}")
if auth_header:
    print("Authorization header present")
else:
    print("No authorization header")
User Agent: Unknown
No authorization header

Conclusion

Apache CGI automatically converts HTTP headers to environment variables with HTTP_ prefix. Use os.environ.get() to safely read header values and handle missing headers gracefully.

Updated on: 2026-03-24T20:02:15+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements