0
# HTTP Models
1
2
HTTPie provides data models and utilities for working with HTTP requests, responses, and status codes in both CLI and programmatic contexts.
3
4
```python
5
from httpie.models import HTTPMessage, HTTPRequest, HTTPResponse, RequestsMessage, RequestsMessageKind, OutputOptions, infer_requests_message_kind
6
from httpie.output.models import ProcessingOptions
7
from httpie.status import ExitStatus, http_status_to_exit_status
8
from enum import IntEnum, Enum, auto
9
from typing import Union, Iterable, NamedTuple
10
import requests
11
import argparse
12
```
13
14
## Capabilities
15
16
### Exit Status Codes
17
18
HTTPie uses specific exit codes to indicate different types of request outcomes.
19
20
```python { .api }
21
class ExitStatus(IntEnum):
22
"""Program exit status code constants."""
23
24
SUCCESS = 0 # Request completed successfully
25
ERROR = 1 # General error (network, parsing, etc.)
26
ERROR_TIMEOUT = 2 # Request timed out
27
ERROR_HTTP_3XX = 3 # HTTP 3xx redirection (with --check-status)
28
ERROR_HTTP_4XX = 4 # HTTP 4xx client error (with --check-status)
29
ERROR_HTTP_5XX = 5 # HTTP 5xx server error (with --check-status)
30
ERROR_TOO_MANY_REDIRECTS = 6 # Exceeded maximum redirects
31
PLUGIN_ERROR = 7 # Plugin-related error
32
ERROR_CTRL_C = 130 # Keyboard interrupt (Ctrl+C)
33
```
34
35
### HTTP Status Conversion
36
37
```python { .api }
38
def http_status_to_exit_status(http_status: int, follow: bool = False) -> ExitStatus:
39
"""
40
Convert HTTP status code to HTTPie exit status.
41
42
Args:
43
http_status: HTTP status code (200, 404, 500, etc.)
44
follow: Whether redirects are being followed
45
46
Returns:
47
ExitStatus: Corresponding HTTPie exit status
48
"""
49
```
50
51
### Request and Response Models
52
53
HTTPie provides models for working with HTTP messages programmatically.
54
55
```python { .api }
56
class HTTPMessage:
57
"""Abstract class for HTTP messages."""
58
59
def iter_body(self, chunk_size: int) -> Iterable[bytes]:
60
"""Return an iterator over the body."""
61
62
def iter_lines(self, chunk_size: int) -> Iterable[bytes]:
63
"""Return an iterator over the body yielding lines."""
64
65
@property
66
def headers(self) -> str:
67
"""Return a str with the message's headers."""
68
69
@property
70
def metadata(self) -> str:
71
"""Return metadata about the current message."""
72
73
@property
74
def content_type(self) -> str:
75
"""Return the message content type."""
76
77
class HTTPRequest(HTTPMessage):
78
"""A requests.models.Request wrapper."""
79
80
@property
81
def body(self) -> bytes:
82
"""Request body content."""
83
84
class HTTPResponse(HTTPMessage):
85
"""A requests.models.Response wrapper."""
86
87
@property
88
def version(self) -> str:
89
"""Return the HTTP version used by the server, e.g. '1.1'."""
90
91
RequestsMessage = Union[requests.PreparedRequest, requests.Response]
92
"""Type alias for HTTP request or response messages."""
93
94
class RequestsMessageKind(Enum):
95
"""Type of HTTP message."""
96
REQUEST = auto()
97
RESPONSE = auto()
98
99
def infer_requests_message_kind(message: RequestsMessage) -> RequestsMessageKind:
100
"""Infer the kind of requests message."""
101
```
102
103
### Output Configuration Models
104
105
Control what parts of HTTP messages are displayed.
106
107
```python { .api }
108
class OutputOptions(NamedTuple):
109
"""Configuration for HTTPie output display."""
110
kind: RequestsMessageKind
111
headers: bool
112
body: bool
113
meta: bool = False
114
115
def any(self) -> bool:
116
"""True if any output option is enabled."""
117
118
@classmethod
119
def from_message(cls, message: RequestsMessage, raw_args: str = '', **kwargs) -> 'OutputOptions':
120
"""
121
Create OutputOptions from message and CLI options.
122
123
Args:
124
message: HTTP message to analyze
125
raw_args: CLI output options string (e.g., 'HhBb')
126
**kwargs: Additional options
127
128
Returns:
129
OutputOptions: Configured output options
130
"""
131
132
class ProcessingOptions:
133
"""Configuration for message processing and formatting."""
134
135
@classmethod
136
def from_raw_args(cls, args: argparse.Namespace) -> 'ProcessingOptions':
137
"""
138
Create ProcessingOptions from parsed CLI arguments.
139
140
Args:
141
args: Parsed command-line arguments
142
143
Returns:
144
ProcessingOptions: Processing configuration
145
"""
146
```
147
148
### Environment Model
149
150
The Environment class encapsulates HTTPie's execution context.
151
152
```python { .api }
153
class Environment:
154
"""HTTPie execution environment and context."""
155
156
def __init__(self,
157
stdin: IO = None,
158
stdout: IO = None,
159
stderr: IO = None,
160
config_dir: str = None):
161
"""
162
Initialize environment.
163
164
Args:
165
stdin: Standard input stream
166
stdout: Standard output stream
167
stderr: Standard error stream
168
config_dir: Configuration directory path
169
"""
170
171
@property
172
def program_name(self) -> str:
173
"""Name of the executing program (http, https, httpie)."""
174
175
@property
176
def stdin_encoding(self) -> str:
177
"""Encoding for standard input."""
178
179
@property
180
def is_windows(self) -> bool:
181
"""True if running on Windows."""
182
183
@property
184
def stdout_isatty(self) -> bool:
185
"""True if stdout is connected to a terminal."""
186
187
@property
188
def config(self) -> Config:
189
"""HTTPie configuration instance."""
190
191
def log_error(self, message: str, level: LogLevel = LogLevel.ERROR) -> None:
192
"""
193
Log error message to stderr.
194
195
Args:
196
message: Error message to log
197
level: Logging level
198
"""
199
200
def as_silent(self) -> ContextManager:
201
"""Context manager that suppresses output temporarily."""
202
```
203
204
### HTTP Client Models
205
206
Models for building and sending HTTP requests.
207
208
```python { .api }
209
class HTTPRequest:
210
"""HTTP request representation."""
211
212
method: str # HTTP method (GET, POST, etc.)
213
url: str # Request URL
214
headers: Dict[str, str] # Request headers
215
body: Union[str, bytes] # Request body
216
auth: requests.auth.AuthBase # Authentication handler
217
218
class HTTPResponse:
219
"""HTTP response representation."""
220
221
status_code: int # HTTP status code
222
headers: Dict[str, str] # Response headers
223
body: Union[str, bytes] # Response body
224
elapsed: float # Request duration in seconds
225
```
226
227
### Utility Functions
228
229
```python { .api }
230
def unwrap_context(exception: Exception) -> Exception:
231
"""
232
Unwrap exception context to find root cause.
233
234
Args:
235
exception: Exception with potential context chain
236
237
Returns:
238
Exception: Root exception in the context chain
239
"""
240
241
def humanize_bytes(n: int, precision: int = 2) -> str:
242
"""
243
Convert byte count to human-readable format.
244
245
Args:
246
n: Number of bytes
247
precision: Decimal places for formatting
248
249
Returns:
250
str: Human-readable size (e.g., '1.5 MB')
251
"""
252
253
def repr_dict(d: Dict) -> str:
254
"""
255
Create readable string representation of dictionary.
256
257
Args:
258
d: Dictionary to represent
259
260
Returns:
261
str: Formatted dictionary representation
262
"""
263
```
264
265
### Error Models
266
267
HTTPie defines specific exception types for different error conditions.
268
269
```python { .api }
270
class HTTPieError(Exception):
271
"""Base exception for HTTPie-specific errors."""
272
pass
273
274
class ConfigFileError(HTTPieError):
275
"""Configuration file parsing or validation error."""
276
pass
277
278
class SessionError(HTTPieError):
279
"""Session storage or retrieval error."""
280
pass
281
282
class PluginError(HTTPieError):
283
"""Plugin loading or execution error."""
284
pass
285
```
286
287
### Usage Examples
288
289
#### Working with Exit Codes
290
291
```python
292
from httpie.core import main
293
from httpie.context import Environment
294
from httpie.status import ExitStatus
295
296
env = Environment()
297
exit_status = main(['http', 'httpie.io/hello'], env)
298
299
if exit_status == ExitStatus.SUCCESS:
300
print("Request successful")
301
elif exit_status == ExitStatus.ERROR_TIMEOUT:
302
print("Request timed out")
303
elif exit_status in [ExitStatus.ERROR_HTTP_4XX, ExitStatus.ERROR_HTTP_5XX]:
304
print("HTTP error occurred")
305
```
306
307
#### Custom Output Processing
308
309
```python
310
from httpie.models import OutputOptions, RequestsMessageKind
311
from httpie.output.writer import write_message
312
313
# Configure output to show only response body
314
output_options = OutputOptions(
315
headers=False,
316
body=True,
317
kind=RequestsMessageKind.RESPONSE
318
)
319
320
# Process and display HTTP message
321
write_message(
322
requests_message=response_message,
323
env=env,
324
output_options=output_options,
325
processing_options=processing_options
326
)
327
```
328
329
#### Environment Customization
330
331
```python
332
import sys
333
from httpie.context import Environment
334
335
# Custom environment for testing
336
env = Environment(
337
stdin=sys.stdin,
338
stdout=sys.stdout,
339
stderr=sys.stderr,
340
config_dir='/tmp/httpie-test-config'
341
)
342
343
# Use custom environment
344
exit_status = main(['http', 'example.com'], env)
345
```