Typing Stubs for httplib2

0.31.2.20260408 · active · verified Fri Apr 10

types-httplib2 provides PEP 561 compliant typing stubs for the httplib2 HTTP client library. As part of the typeshed project, its purpose is to enable static type checking for code using httplib2, without altering runtime behavior. The current version is 0.31.2.20260408, with updates released automatically (up to once a day) by typeshed machinery when the underlying library changes or type definitions improve.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a basic HTTP GET request using httplib2. With `types-httplib2` installed, static type checkers like MyPy will automatically use the provided stub files to verify type consistency for httplib2 objects and methods, as shown in the `process_response` function example.

import httplib2
import os

# Create an HTTP object, optionally with a cache directory.
# For a real application, consider a more robust cache path or managing it.
h = httplib2.Http(os.path.join(os.path.dirname(__file__), ".cache"))

# Make a simple GET request to a public test API
try:
    resp, content = h.request("https://jsonplaceholder.typicode.com/todos/1", "GET")

    # The 'resp' object (type: httplib2.Response) contains headers and status
    print(f"Status: {resp.status}")
    print(f"Content-Type: {resp['content-type']}")

    # The 'content' (type: bytes) is the response body. Decode it if expecting text.
    if resp.status == 200:
        data = content.decode('utf-8')
        print(f"Content: {data[:100]}...") # Print first 100 chars
    else:
        print(f"Error fetching data: {content.decode('utf-8')}")

except httplib2.ServerNotFoundError:
    print("Server not found. Check your internet connection or the URL.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

# Example of how type checking would apply:
def process_response(response: httplib2.Response, body: bytes) -> tuple[int, str]:
    """Processes an httplib2 response and its body."""
    if response.status == 200:
        # mypy will check if response.status is int and body.decode returns str
        return response.status, body.decode('utf-8')
    # mypy will check types of response.status and response.reason
    return response.status, f"Error: {response.reason.decode('utf-8')}"

# To type-check this code:
# 1. Save the above code as e.g., `my_app.py`
# 2. Install httplib2 and types-httplib2: `pip install httplib2 types-httplib2`
# 3. Run mypy from your terminal: `mypy my_app.py`
#    Mypy will use the stubs from `types-httplib2` to check the types of `resp`, `content`, and parameters/returns in `process_response`.

view raw JSON →