or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli.mdclient.mdconfiguration.mdindex.mdmodels.mdplugins.mdsessions.mdutilities.md

sessions.mddocs/

0

# Session Management

1

2

HTTPie's session management system allows you to persist cookies, authentication credentials, custom headers, and other request data across multiple HTTP requests.

3

4

```python

5

from httpie.sessions import Session, get_httpie_session, is_anonymous_session

6

from httpie.context import Environment

7

from httpie.cli.dicts import HTTPHeadersDict

8

from pathlib import Path

9

from typing import Dict, Any, Optional

10

```

11

12

## Capabilities

13

14

### Session Class

15

16

The core session management functionality for storing and retrieving persistent request data.

17

18

```python { .api }

19

class Session:

20

"""HTTPie session for persistent request data."""

21

22

def __init__(self, session_dir: str):

23

"""

24

Initialize session with storage directory.

25

26

Args:

27

session_dir: Directory path for session storage

28

"""

29

30

def load(self) -> Dict[str, Any]:

31

"""

32

Load session data from storage.

33

34

Returns:

35

dict: Session data containing cookies, auth, headers, etc.

36

"""

37

38

def save(self) -> None:

39

"""Save current session data to storage."""

40

41

42

def update_headers(self, request_headers: HTTPHeadersDict) -> None:

43

"""

44

Update session headers with request headers while ignoring certain name prefixes.

45

46

Args:

47

request_headers: Request headers to merge into session

48

"""

49

50

@property

51

def is_new(self) -> bool:

52

"""True if this is a new session (not loaded from storage)."""

53

```

54

55

### Session Factory Function

56

57

```python { .api }

58

def get_httpie_session(

59

env: Environment,

60

config_dir: Path,

61

session_name: str,

62

host: Optional[str],

63

url: str,

64

*,

65

suppress_legacy_warnings: bool = False

66

) -> Session:

67

"""

68

Get or create HTTPie session for persistent data storage.

69

70

Args:

71

env: HTTPie environment instance

72

config_dir: HTTPie configuration directory

73

session_name: Name of the session

74

host: Host for session scoping

75

url: Full URL for session scoping

76

77

Returns:

78

Session: Session instance for the given name and host

79

"""

80

```

81

82

### Command-Line Session Usage

83

84

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

85

86

#### Creating and Using Sessions

87

88

```bash { .api }

89

# Create session with authentication

90

http --session=myapi -a user:pass api.example.com/login

91

92

# Subsequent requests use stored auth and cookies

93

http --session=myapi api.example.com/user/profile

94

95

# Sessions persist custom headers

96

http --session=myapi api.example.com/data X-Custom-Header:value

97

98

# Session data is automatically saved after each request

99

http --session=myapi PUT api.example.com/user/settings name=John

100

```

101

102

#### Session Scoping

103

104

Sessions are scoped by hostname to prevent credential leakage:

105

106

```bash

107

# Different hosts use separate session data

108

http --session=api api.example.com/login # Stores cookies for api.example.com

109

http --session=api other.example.com/data # Uses separate cookies for other.example.com

110

```

111

112

### Session Data Structure

113

114

Session files are stored as JSON and contain:

115

116

```json

117

{

118

"auth": {

119

"type": "basic",

120

"username": "user",

121

"password": "pass"

122

},

123

"cookies": {

124

"sessionid": "abc123",

125

"csrf_token": "xyz789"

126

},

127

"headers": {

128

"User-Agent": "HTTPie/3.2.4",

129

"X-API-Version": "v2"

130

}

131

}

132

```

133

134

### Session Storage Locations

135

136

Sessions are stored in the HTTPie configuration directory:

137

138

- **Linux/macOS**: `~/.config/httpie/sessions/`

139

- **Windows**: `%APPDATA%\httpie\sessions\`

140

141

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

142

143

### Programmatic Session Usage

144

145

```python { .api }

146

from httpie.sessions import get_httpie_session

147

from httpie.context import Environment

148

149

# Create environment and get session

150

env = Environment()

151

session = get_httpie_session(

152

env=env,

153

config_dir=env.config_dir,

154

session_name='myapi',

155

host='api.example.com',

156

url='https://api.example.com'

157

)

158

159

# Load existing session data

160

if not session.is_new:

161

data = session.load()

162

print(f"Loaded session with {len(data.get('cookies', {}))} cookies")

163

164

# Update session headers

165

session.update_headers({

166

'X-API-Version': 'v3',

167

'X-Client-ID': 'my-app'

168

})

169

170

# Save session data

171

session.save()

172

```

173

174

### Session Management Commands

175

176

The `httpie sessions` command provides session management functionality:

177

178

```bash { .api }

179

# List all sessions

180

httpie sessions list

181

182

# Show session details

183

httpie sessions show myapi api.example.com

184

185

# Delete a session

186

httpie sessions delete myapi api.example.com

187

188

# Export session data

189

httpie sessions export myapi api.example.com > session-backup.json

190

```

191

192

### Session Security

193

194

- **Permissions**: Session files are created with restricted permissions (600) for security

195

- **Encryption**: Session data is stored in plain text - avoid using on shared systems

196

- **Scoping**: Sessions are hostname-scoped to prevent credential leakage between domains

197

- **Cleanup**: Use `httpie sessions delete` to remove sensitive session data

198

199

### Session Lifecycle

200

201

1. **Creation**: First use of `--session=name` creates new session

202

2. **Storage**: Session data is saved after each successful request

203

3. **Loading**: Subsequent requests with same session name load stored data

204

4. **Updates**: New cookies, auth changes, and headers are merged into session

205

5. **Persistence**: Sessions persist until explicitly deleted

206

207

### Advanced Session Features

208

209

#### Session Inheritance

210

211

```bash

212

# Base session with common settings

213

http --session=base api.example.com/setup X-Version:v2

214

215

# Inherit from base session (copies existing data)

216

http --session=user1 --session-read-only=base api.example.com/login -a user1:pass

217

218

# user1 session gets X-Version header from base but adds its own auth

219

```

220

221

#### Read-Only Sessions

222

223

```bash

224

# Use session data without modifying it

225

http --session-read-only=myapi api.example.com/data

226

227

# Useful for testing without affecting stored session

228

```

229

230

### Error Handling

231

232

Session operations may fail in several scenarios:

233

234

- **Permission Errors**: Insufficient permissions to read/write session files

235

- **JSON Errors**: Corrupted session files with invalid JSON

236

- **Directory Errors**: Missing or inaccessible configuration directory

237

238

```python

239

from httpie.sessions import Session, SessionError

240

241

try:

242

session = get_httpie_session(env, config_dir, 'myapi', 'api.example.com', url)

243

session.save()

244

except SessionError as e:

245

print(f"Session error: {e}")

246

except PermissionError as e:

247

print(f"Permission denied: {e}")

248

```