HTTPie: modern, user-friendly command-line HTTP client for the API era.
—
HTTPie's session management system allows you to persist cookies, authentication credentials, custom headers, and other request data across multiple HTTP requests.
from httpie.sessions import Session, get_httpie_session, is_anonymous_session
from httpie.context import Environment
from httpie.cli.dicts import HTTPHeadersDict
from pathlib import Path
from typing import Dict, Any, OptionalThe core session management functionality for storing and retrieving persistent request data.
class Session:
"""HTTPie session for persistent request data."""
def __init__(self, session_dir: str):
"""
Initialize session with storage directory.
Args:
session_dir: Directory path for session storage
"""
def load(self) -> Dict[str, Any]:
"""
Load session data from storage.
Returns:
dict: Session data containing cookies, auth, headers, etc.
"""
def save(self) -> None:
"""Save current session data to storage."""
def update_headers(self, request_headers: HTTPHeadersDict) -> None:
"""
Update session headers with request headers while ignoring certain name prefixes.
Args:
request_headers: Request headers to merge into session
"""
@property
def is_new(self) -> bool:
"""True if this is a new session (not loaded from storage)."""def get_httpie_session(
env: Environment,
config_dir: Path,
session_name: str,
host: Optional[str],
url: str,
*,
suppress_legacy_warnings: bool = False
) -> Session:
"""
Get or create HTTPie session for persistent data storage.
Args:
env: HTTPie environment instance
config_dir: HTTPie configuration directory
session_name: Name of the session
host: Host for session scoping
url: Full URL for session scoping
Returns:
Session: Session instance for the given name and host
"""Sessions are managed through the --session option in HTTPie commands.
# Create session with authentication
http --session=myapi -a user:pass api.example.com/login
# Subsequent requests use stored auth and cookies
http --session=myapi api.example.com/user/profile
# Sessions persist custom headers
http --session=myapi api.example.com/data X-Custom-Header:value
# Session data is automatically saved after each request
http --session=myapi PUT api.example.com/user/settings name=JohnSessions are scoped by hostname to prevent credential leakage:
# Different hosts use separate session data
http --session=api api.example.com/login # Stores cookies for api.example.com
http --session=api other.example.com/data # Uses separate cookies for other.example.comSession files are stored as JSON and contain:
{
"auth": {
"type": "basic",
"username": "user",
"password": "pass"
},
"cookies": {
"sessionid": "abc123",
"csrf_token": "xyz789"
},
"headers": {
"User-Agent": "HTTPie/3.2.4",
"X-API-Version": "v2"
}
}Sessions are stored in the HTTPie configuration directory:
~/.config/httpie/sessions/%APPDATA%\httpie\sessions\Session files are named using the pattern: {host}_{session_name}.json
from httpie.sessions import get_httpie_session
from httpie.context import Environment
# Create environment and get session
env = Environment()
session = get_httpie_session(
env=env,
config_dir=env.config_dir,
session_name='myapi',
host='api.example.com',
url='https://api.example.com'
)
# Load existing session data
if not session.is_new:
data = session.load()
print(f"Loaded session with {len(data.get('cookies', {}))} cookies")
# Update session headers
session.update_headers({
'X-API-Version': 'v3',
'X-Client-ID': 'my-app'
})
# Save session data
session.save()The httpie sessions command provides session management functionality:
# List all sessions
httpie sessions list
# Show session details
httpie sessions show myapi api.example.com
# Delete a session
httpie sessions delete myapi api.example.com
# Export session data
httpie sessions export myapi api.example.com > session-backup.jsonhttpie sessions delete to remove sensitive session data--session=name creates new session# Base session with common settings
http --session=base api.example.com/setup X-Version:v2
# Inherit from base session (copies existing data)
http --session=user1 --session-read-only=base api.example.com/login -a user1:pass
# user1 session gets X-Version header from base but adds its own auth# Use session data without modifying it
http --session-read-only=myapi api.example.com/data
# Useful for testing without affecting stored sessionSession operations may fail in several scenarios:
from httpie.sessions import Session, SessionError
try:
session = get_httpie_session(env, config_dir, 'myapi', 'api.example.com', url)
session.save()
except SessionError as e:
print(f"Session error: {e}")
except PermissionError as e:
print(f"Permission denied: {e}")Install with Tessl CLI
npx tessl i tessl/pypi-httpie