CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-httpie

HTTPie: modern, user-friendly command-line HTTP client for the API era.

Pending
Overview
Eval results
Files

models.mddocs/

HTTP Models

HTTPie provides data models and utilities for working with HTTP requests, responses, and status codes in both CLI and programmatic contexts.

from httpie.models import HTTPMessage, HTTPRequest, HTTPResponse, RequestsMessage, RequestsMessageKind, OutputOptions, infer_requests_message_kind
from httpie.output.models import ProcessingOptions
from httpie.status import ExitStatus, http_status_to_exit_status
from enum import IntEnum, Enum, auto
from typing import Union, Iterable, NamedTuple
import requests
import argparse

Capabilities

Exit Status Codes

HTTPie uses specific exit codes to indicate different types of request outcomes.

class ExitStatus(IntEnum):
    """Program exit status code constants."""
    
    SUCCESS = 0                    # Request completed successfully
    ERROR = 1                      # General error (network, parsing, etc.)
    ERROR_TIMEOUT = 2              # Request timed out
    ERROR_HTTP_3XX = 3             # HTTP 3xx redirection (with --check-status)
    ERROR_HTTP_4XX = 4             # HTTP 4xx client error (with --check-status)
    ERROR_HTTP_5XX = 5             # HTTP 5xx server error (with --check-status)
    ERROR_TOO_MANY_REDIRECTS = 6   # Exceeded maximum redirects
    PLUGIN_ERROR = 7               # Plugin-related error
    ERROR_CTRL_C = 130             # Keyboard interrupt (Ctrl+C)

HTTP Status Conversion

def http_status_to_exit_status(http_status: int, follow: bool = False) -> ExitStatus:
    """
    Convert HTTP status code to HTTPie exit status.
    
    Args:
        http_status: HTTP status code (200, 404, 500, etc.)
        follow: Whether redirects are being followed
        
    Returns:
        ExitStatus: Corresponding HTTPie exit status
    """

Request and Response Models

HTTPie provides models for working with HTTP messages programmatically.

class HTTPMessage:
    """Abstract class for HTTP messages."""
    
    def iter_body(self, chunk_size: int) -> Iterable[bytes]:
        """Return an iterator over the body."""
    
    def iter_lines(self, chunk_size: int) -> Iterable[bytes]:
        """Return an iterator over the body yielding lines."""
    
    @property
    def headers(self) -> str:
        """Return a str with the message's headers."""
    
    @property
    def metadata(self) -> str:
        """Return metadata about the current message."""
    
    @property
    def content_type(self) -> str:
        """Return the message content type."""

class HTTPRequest(HTTPMessage):
    """A requests.models.Request wrapper."""
    
    @property
    def body(self) -> bytes:
        """Request body content."""

class HTTPResponse(HTTPMessage):
    """A requests.models.Response wrapper."""
    
    @property
    def version(self) -> str:
        """Return the HTTP version used by the server, e.g. '1.1'."""

RequestsMessage = Union[requests.PreparedRequest, requests.Response]
"""Type alias for HTTP request or response messages."""

class RequestsMessageKind(Enum):
    """Type of HTTP message."""
    REQUEST = auto()
    RESPONSE = auto()

def infer_requests_message_kind(message: RequestsMessage) -> RequestsMessageKind:
    """Infer the kind of requests message."""

Output Configuration Models

Control what parts of HTTP messages are displayed.

class OutputOptions(NamedTuple):
    """Configuration for HTTPie output display."""
    kind: RequestsMessageKind
    headers: bool
    body: bool
    meta: bool = False
    
    def any(self) -> bool:
        """True if any output option is enabled."""
    
    @classmethod
    def from_message(cls, message: RequestsMessage, raw_args: str = '', **kwargs) -> 'OutputOptions':
        """
        Create OutputOptions from message and CLI options.
        
        Args:
            message: HTTP message to analyze
            raw_args: CLI output options string (e.g., 'HhBb')
            **kwargs: Additional options
            
        Returns:
            OutputOptions: Configured output options
        """

class ProcessingOptions:
    """Configuration for message processing and formatting."""
    
    @classmethod
    def from_raw_args(cls, args: argparse.Namespace) -> 'ProcessingOptions':
        """
        Create ProcessingOptions from parsed CLI arguments.
        
        Args:
            args: Parsed command-line arguments
            
        Returns:
            ProcessingOptions: Processing configuration
        """

Environment Model

The Environment class encapsulates HTTPie's execution context.

class Environment:
    """HTTPie execution environment and context."""
    
    def __init__(self, 
                 stdin: IO = None,
                 stdout: IO = None, 
                 stderr: IO = None,
                 config_dir: str = None):
        """
        Initialize environment.
        
        Args:
            stdin: Standard input stream
            stdout: Standard output stream  
            stderr: Standard error stream
            config_dir: Configuration directory path
        """
    
    @property
    def program_name(self) -> str:
        """Name of the executing program (http, https, httpie)."""
    
    @property
    def stdin_encoding(self) -> str:
        """Encoding for standard input."""
    
    @property
    def is_windows(self) -> bool:
        """True if running on Windows."""
    
    @property
    def stdout_isatty(self) -> bool:
        """True if stdout is connected to a terminal."""
    
    @property
    def config(self) -> Config:
        """HTTPie configuration instance."""
    
    def log_error(self, message: str, level: LogLevel = LogLevel.ERROR) -> None:
        """
        Log error message to stderr.
        
        Args:
            message: Error message to log
            level: Logging level
        """
    
    def as_silent(self) -> ContextManager:
        """Context manager that suppresses output temporarily."""

HTTP Client Models

Models for building and sending HTTP requests.

class HTTPRequest:
    """HTTP request representation."""
    
    method: str                    # HTTP method (GET, POST, etc.)
    url: str                      # Request URL
    headers: Dict[str, str]       # Request headers
    body: Union[str, bytes]       # Request body
    auth: requests.auth.AuthBase  # Authentication handler

class HTTPResponse:
    """HTTP response representation."""
    
    status_code: int              # HTTP status code
    headers: Dict[str, str]       # Response headers  
    body: Union[str, bytes]       # Response body
    elapsed: float               # Request duration in seconds

Utility Functions

def unwrap_context(exception: Exception) -> Exception:
    """
    Unwrap exception context to find root cause.
    
    Args:
        exception: Exception with potential context chain
        
    Returns:
        Exception: Root exception in the context chain
    """

def humanize_bytes(n: int, precision: int = 2) -> str:
    """
    Convert byte count to human-readable format.
    
    Args:
        n: Number of bytes
        precision: Decimal places for formatting
        
    Returns:
        str: Human-readable size (e.g., '1.5 MB')
    """

def repr_dict(d: Dict) -> str:
    """
    Create readable string representation of dictionary.
    
    Args:
        d: Dictionary to represent
        
    Returns:
        str: Formatted dictionary representation
    """

Error Models

HTTPie defines specific exception types for different error conditions.

class HTTPieError(Exception):
    """Base exception for HTTPie-specific errors."""
    pass

class ConfigFileError(HTTPieError):
    """Configuration file parsing or validation error."""
    pass

class SessionError(HTTPieError):
    """Session storage or retrieval error."""
    pass

class PluginError(HTTPieError):
    """Plugin loading or execution error."""
    pass

Usage Examples

Working with Exit Codes

from httpie.core import main
from httpie.context import Environment
from httpie.status import ExitStatus

env = Environment()
exit_status = main(['http', 'httpie.io/hello'], env)

if exit_status == ExitStatus.SUCCESS:
    print("Request successful")
elif exit_status == ExitStatus.ERROR_TIMEOUT:
    print("Request timed out")
elif exit_status in [ExitStatus.ERROR_HTTP_4XX, ExitStatus.ERROR_HTTP_5XX]:
    print("HTTP error occurred")

Custom Output Processing

from httpie.models import OutputOptions, RequestsMessageKind
from httpie.output.writer import write_message

# Configure output to show only response body
output_options = OutputOptions(
    headers=False,
    body=True,
    kind=RequestsMessageKind.RESPONSE
)

# Process and display HTTP message
write_message(
    requests_message=response_message,
    env=env,
    output_options=output_options,
    processing_options=processing_options
)

Environment Customization

import sys
from httpie.context import Environment

# Custom environment for testing
env = Environment(
    stdin=sys.stdin,
    stdout=sys.stdout,
    stderr=sys.stderr,
    config_dir='/tmp/httpie-test-config'
)

# Use custom environment
exit_status = main(['http', 'example.com'], env)

Install with Tessl CLI

npx tessl i tessl/pypi-httpie

docs

cli.md

client.md

configuration.md

index.md

models.md

plugins.md

sessions.md

utilities.md

tile.json