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

sessions.mddocs/

Session Management

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, Optional

Capabilities

Session Class

The 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)."""

Session Factory Function

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
    """

Command-Line Session Usage

Sessions are managed through the --session option in HTTPie commands.

Creating and Using Sessions

# 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=John

Session Scoping

Sessions 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.com

Session Data Structure

Session 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"
  }
}

Session Storage Locations

Sessions are stored in the HTTPie configuration directory:

  • Linux/macOS: ~/.config/httpie/sessions/
  • Windows: %APPDATA%\httpie\sessions\

Session files are named using the pattern: {host}_{session_name}.json

Programmatic Session Usage

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()

Session Management Commands

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.json

Session Security

  • Permissions: Session files are created with restricted permissions (600) for security
  • Encryption: Session data is stored in plain text - avoid using on shared systems
  • Scoping: Sessions are hostname-scoped to prevent credential leakage between domains
  • Cleanup: Use httpie sessions delete to remove sensitive session data

Session Lifecycle

  1. Creation: First use of --session=name creates new session
  2. Storage: Session data is saved after each successful request
  3. Loading: Subsequent requests with same session name load stored data
  4. Updates: New cookies, auth changes, and headers are merged into session
  5. Persistence: Sessions persist until explicitly deleted

Advanced Session Features

Session Inheritance

# 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

Read-Only Sessions

# Use session data without modifying it
http --session-read-only=myapi api.example.com/data

# Useful for testing without affecting stored session

Error Handling

Session operations may fail in several scenarios:

  • Permission Errors: Insufficient permissions to read/write session files
  • JSON Errors: Corrupted session files with invalid JSON
  • Directory Errors: Missing or inaccessible configuration directory
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

docs

cli.md

client.md

configuration.md

index.md

models.md

plugins.md

sessions.md

utilities.md

tile.json