HTTPie: modern, user-friendly command-line HTTP client for the API era.
—
HTTPie provides various constants, utility functions, and helper classes for HTTP processing and command-line parsing.
from httpie.cli.constants import *
from httpie.utils import *
from httpie.status import ExitStatus
from typing import Any, List, Optional, Tuple, Dict
import enumStandard HTTP method constants used throughout HTTPie.
HTTP_GET: str = 'GET'
HTTP_POST: str = 'POST'
HTTP_OPTIONS: str = 'OPTIONS'Constants defining separators for parsing command-line request items.
# Header separators
SEPARATOR_HEADER: str = ':'
SEPARATOR_HEADER_EMPTY: str = ';'
SEPARATOR_HEADER_EMBED: str = ':@'
# Data separators
SEPARATOR_DATA_STRING: str = '='
SEPARATOR_DATA_RAW_JSON: str = ':='
SEPARATOR_DATA_EMBED_FILE_CONTENTS: str = '=@'
SEPARATOR_DATA_EMBED_RAW_JSON_FILE: str = ':=@'
# File upload separator
SEPARATOR_FILE_UPLOAD: str = '@'
# Query parameter separators
SEPARATOR_QUERY_PARAM: str = '=='
SEPARATOR_QUERY_EMBED_FILE: str = '==@'
# Separator groups
SEPARATOR_GROUP_DATA_ITEMS: frozenset
SEPARATORS_GROUP_MULTIPART: frozenset
SEPARATOR_GROUP_ALL_ITEMS: frozensetConstants for controlling HTTPie output display.
# Output option characters
OUT_REQ_HEAD: str = 'H' # Request headers
OUT_REQ_BODY: str = 'B' # Request body
OUT_RESP_HEAD: str = 'h' # Response headers
OUT_RESP_BODY: str = 'b' # Response body
OUT_RESP_META: str = 'm' # Response metadata
# Output option groups
BASE_OUTPUT_OPTIONS: frozenset
OUTPUT_OPTIONS: frozenset
# Default output configurations
OUTPUT_OPTIONS_DEFAULT: str
OUTPUT_OPTIONS_DEFAULT_STDOUT_REDIRECTED: str
OUTPUT_OPTIONS_DEFAULT_OFFLINE: strConfiguration for output formatting and colorization.
class PrettyOptions(enum.Enum):
STDOUT_TTY_ONLY = enum.auto()
PRETTY_MAP: Dict[str, List[str]] = {
'all': ['format', 'colors'],
'colors': ['colors'],
'format': ['format'],
'none': []
}
DEFAULT_FORMAT_OPTIONS: List[str]
SORTED_FORMAT_OPTIONS: List[str]General utility functions for HTTP processing and data handling.
def load_json_preserve_order_and_dupe_keys(s: str) -> 'JsonDictPreservingDuplicateKeys':
"""Load JSON string preserving order and duplicate keys."""
def humanize_bytes(n: int, precision: int = 2) -> str:
"""Convert byte count to human-readable format."""
def get_content_type(filename: str) -> str:
"""Guess content type from filename."""
def split_cookies(cookie_header: str) -> List[str]:
"""Split Set-Cookie header value into individual cookies."""
def parse_content_type_header(header: str) -> Tuple[str, Dict[str, str]]:
"""Parse Content-Type header into type and parameters."""
def url_as_host(url: str) -> str:
"""Extract hostname from URL."""
def repr_dict(d: dict) -> str:
"""Create readable string representation of dictionary."""
def unwrap_context(exception: Exception) -> Exception:
"""Unwrap exception context to find root cause."""Utility classes for specific HTTP processing needs.
class JsonDictPreservingDuplicateKeys(OrderedDict):
"""A specialized JSON dict preserving duplicate keys."""
SUPPORTS_SORTING: bool
def __init__(self, items: List[Tuple[str, Any]]): ...
class ExplicitNullAuth(requests.auth.AuthBase):
"""Authentication class for explicitly disabling auth."""
def __call__(self, request): ...
class LockFileError(Exception):
"""File locking related error."""
passFunctions for handling HTTP cookies.
def get_expired_cookies(jar: requests.cookies.RequestsCookieJar, host: str) -> List[str]:
"""Get list of expired cookie names for a host."""
def parse_cookie_header(header: str) -> Dict[str, str]:
"""Parse cookie header into name-value pairs."""Utilities for file handling and path operations.
def get_content_type(filename: str) -> Optional[str]:
"""Determine MIME type from filename."""
def is_file_path(value: str) -> bool:
"""Check if string represents a file path."""
def normalize_file_path(path: str) -> str:
"""Normalize file path for cross-platform compatibility."""from httpie.cli.constants import SEPARATOR_DATA_STRING, SEPARATOR_HEADER
def parse_request_item(item: str):
if SEPARATOR_DATA_STRING in item:
key, value = item.split(SEPARATOR_DATA_STRING, 1)
return 'data', key, value
elif SEPARATOR_HEADER in item:
key, value = item.split(SEPARATOR_HEADER, 1)
return 'header', key, value
return 'unknown', item, Nonefrom httpie.utils import humanize_bytes, get_content_type
# Format file sizes
size = humanize_bytes(1536) # Returns "1.5 KB"
# Detect content types
content_type = get_content_type('data.json') # Returns "application/json"from httpie.utils import JsonDictPreservingDuplicateKeys
# Preserve duplicate keys in JSON
data = JsonDictPreservingDuplicateKeys([
("name", "John"),
("name", "Jane"), # Duplicate key preserved
("age", 30)
])
json_str = json.dumps(data, indent=2)from httpie.utils import LockFileError
try:
# File operations that might fail
with file_lock('/tmp/httpie.lock'):
process_data()
except LockFileError as e:
print(f"Could not acquire file lock: {e}")Install with Tessl CLI
npx tessl i tessl/pypi-httpie