CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-httplib2

A comprehensive HTTP client library that supports many features left out of other HTTP libraries.

Pending
Overview
Eval results
Files

http-client.mddocs/

HTTP Client

Core HTTP client functionality providing request/response handling, connection management, caching, and authentication. The Http class serves as the primary interface for all HTTP operations in httplib2.

Capabilities

Http Class

The main HTTP client class that manages connections, handles caching, authentication, redirects, and compression. Supports both HTTP and HTTPS with extensive configuration options.

class Http:
    def __init__(self, cache=None, timeout=None, proxy_info=None,
                 ca_certs=None, disable_ssl_certificate_validation=False,
                 tls_maximum_version=None, tls_minimum_version=None):
        """
        Initialize HTTP client.
        
        Args:
            cache: Cache object or directory path for caching
            timeout (float): Socket timeout in seconds
            proxy_info: ProxyInfo object or function returning ProxyInfo
            ca_certs (str): Path to CA certificates file
            disable_ssl_certificate_validation (bool): Skip SSL cert validation
            tls_maximum_version: Maximum TLS version
            tls_minimum_version: Minimum TLS version
        """
    
    def request(self, uri, method="GET", body=None, headers=None, 
                redirections=5, connection_type=None):
        """
        Perform a single HTTP request.
        
        Args:
            uri (str): Absolute URI of the HTTP resource
            method (str): HTTP method (GET, POST, PUT, DELETE, etc.)
            body (str or bytes): Entity body to send with request
            headers (dict): Extra headers to send with request
            redirections (int): Maximum number of redirects to follow (default 5)
            connection_type: Connection class to use
            
        Returns:
            tuple: (Response, content) where Response contains status/headers
                   and content is the response body as bytes
                   
        Raises:
            HttpLib2Error: Base class for all httplib2 errors
            RedirectLimit: Too many redirects
            ServerNotFoundError: Server hostname not found
            RelativeURIError: URI is relative when absolute required
        """
    
    def add_credentials(self, name, password, domain=""):
        """
        Add credentials for authentication.
        
        Args:
            name (str): Username
            password (str): Password  
            domain (str): Authentication domain (optional)
        """
    
    def add_certificate(self, key, cert, domain, password=None):
        """
        Add client certificate for authentication.
        
        Args:
            key (str): Path to private key file
            cert (str): Path to certificate file
            domain (str): Domain for certificate usage
            password (str): Private key password (optional)
        """
    
    def clear_credentials(self):
        """Remove all stored authentication credentials."""
    
    def close(self):
        """
        Close persistent connections and clear sensitive data.
        Not thread-safe, requires external synchronization.
        """

Usage Examples

Basic GET Request

import httplib2

h = httplib2.Http()
(resp, content) = h.request("http://example.org/")
print(f"Status: {resp.status}")
print(f"Content-Type: {resp['content-type']}")
print(f"Body: {content.decode('utf-8')}")

POST Request with Body and Headers

import httplib2

h = httplib2.Http()
body = '{"key": "value"}'
headers = {
    'content-type': 'application/json',
    'user-agent': 'MyApp/1.0'
}

(resp, content) = h.request(
    "https://api.example.com/data", 
    "POST",
    body=body,
    headers=headers
)

Request with Authentication

import httplib2

h = httplib2.Http()
h.add_credentials('username', 'password', 'api.example.com')

(resp, content) = h.request("https://api.example.com/protected")

Request with Caching

import httplib2

# Use file-based cache in .cache directory
h = httplib2.Http(".cache")

# First request - fetches from server and caches
(resp, content) = h.request("http://example.org/")

# Second request - may use cached version if valid
(resp, content) = h.request("http://example.org/")

# Force fresh request ignoring cache
headers = {'cache-control': 'no-cache'}
(resp, content) = h.request("http://example.org/", headers=headers)

Request with Custom SSL Configuration

import httplib2

h = httplib2.Http(
    ca_certs="/path/to/cacerts.pem",
    disable_ssl_certificate_validation=False,
    tls_minimum_version="TLSv1_2"
)

(resp, content) = h.request("https://secure.example.com/")

Request with Proxy

import httplib2

proxy_info = httplib2.ProxyInfo(
    httplib2.socks.PROXY_TYPE_HTTP, 
    'proxy.example.com', 
    8080,
    proxy_user='proxyuser',
    proxy_pass='proxypass'
)

h = httplib2.Http(proxy_info=proxy_info)
(resp, content) = h.request("http://example.org/")

Connection Management

httplib2 automatically manages HTTP connections:

  • Keep-Alive: Reuses connections when possible for better performance
  • Connection Pool: Maintains pool of connections per hostname
  • Timeout Handling: Configurable socket timeouts
  • SSL/TLS: Full HTTPS support with certificate validation
  • Proxy Support: HTTP, HTTPS, and SOCKS proxy support

HTTP Methods

All HTTP methods are supported:

  • GET: Retrieve data from server
  • POST: Send data to server
  • PUT: Update resource on server
  • DELETE: Remove resource from server
  • HEAD: Get headers only (no body)
  • PATCH: Partial resource update
  • OPTIONS: Get allowed methods
  • TRACE: Echo request for debugging

Content Handling

  • Automatic Decompression: Handles gzip and deflate compression
  • Content-Type: Preserves original content-type headers
  • Encoding: Returns content as bytes, preserving original encoding
  • Chunked Transfer: Supports chunked transfer encoding
  • Content-Length: Handles both fixed-length and streaming content

Redirect Handling

  • Automatic Redirects: Follows 3XX redirects for GET requests
  • Redirect Limits: Configurable maximum redirect count (default 5)
  • Status Codes: Handles 300, 301, 302, 303, 307, 308 redirects
  • Location Header: Validates and follows Location header values
  • Permanent Redirects: Caches 301 redirects to avoid future requests

Install with Tessl CLI

npx tessl i tessl/pypi-httplib2

docs

authentication.md

caching.md

error-handling.md

http-client.md

index.md

proxy-support.md

response-handling.md

utilities.md

tile.json