0
# HTTP Utilities
1
2
HTTP-specific metadata collection, request tracing utilities, and trace header propagation for distributed web applications. These utilities help with HTTP request/response tracing and trace context propagation.
3
4
## Capabilities
5
6
### HTTP Metadata Collection
7
8
Attach HTTP-specific metadata to segments and subsegments for web request tracing.
9
10
```python { .api }
11
# Segment/Subsegment methods for HTTP metadata
12
def put_http_meta(self, key: str, value: Any) -> None:
13
"""
14
Add HTTP-specific metadata to the trace entity.
15
16
Args:
17
key (str): HTTP metadata key ('url', 'method', 'user_agent', 'client_ip', etc.)
18
value (Any): HTTP metadata value
19
20
Common Keys:
21
- 'url': Request URL
22
- 'method': HTTP method (GET, POST, etc.)
23
- 'user_agent': User-Agent header
24
- 'client_ip': Client IP address
25
- 'x_forwarded_for': X-Forwarded-For header
26
- 'request': Request details
27
- 'response': Response details
28
"""
29
30
def apply_status_code(self, status_code: int) -> None:
31
"""
32
Apply HTTP status code effects to the trace entity.
33
34
Args:
35
status_code (int): HTTP status code
36
37
Effects:
38
- 4xx codes: Sets error flag
39
- 5xx codes: Sets fault flag
40
- 429: Sets throttle flag
41
"""
42
43
def set_user(self, user: str) -> None:
44
"""
45
Set user identifier for the segment (indexable in X-Ray console).
46
47
Args:
48
user (str): User identifier
49
50
Notes:
51
- Only available on segments, not subsegments
52
- Creates searchable annotation in X-Ray console
53
- Useful for user-specific trace filtering
54
"""
55
```
56
57
### Trace Header Management
58
59
Handle X-Ray trace headers for distributed tracing across HTTP requests.
60
61
```python { .api }
62
class TraceHeader:
63
"""Represents X-Ray trace header for HTTP request propagation."""
64
65
def __init__(self, root: str = None, parent: str = None, sampled: int = None, data: str = None):
66
"""
67
Create a trace header object.
68
69
Args:
70
root (str): Root trace ID
71
parent (str): Parent segment/subsegment ID
72
sampled (int): Sampling decision (0=not sampled, 1=sampled, None=unknown)
73
data (str): Additional trace data
74
"""
75
76
@classmethod
77
def from_header_str(cls, header: str) -> 'TraceHeader':
78
"""
79
Parse X-Ray trace header string into TraceHeader object.
80
81
Args:
82
header (str): X-Ray trace header string
83
84
Returns:
85
TraceHeader: Parsed trace header object
86
87
Header Format:
88
Root=1-5e8b2e3a-3f1b2c4d5e6f7a8b9c0d1e2f;Parent=1234567890abcdef;Sampled=1
89
"""
90
91
def to_header_str(self) -> str:
92
"""
93
Convert trace header to X-Ray header string format.
94
95
Returns:
96
str: X-Ray trace header string
97
"""
98
99
# Properties
100
@property
101
def data(self) -> str:
102
"""Additional trace data fields."""
103
```
104
105
### Usage Examples
106
107
#### Web Framework Integration
108
109
Manual HTTP metadata collection in web applications:
110
111
```python
112
from aws_xray_sdk.core import xray_recorder
113
from aws_xray_sdk.core.models.trace_header import TraceHeader
114
115
def handle_request(request):
116
# Parse incoming trace header
117
trace_header_str = request.headers.get('X-Amzn-Trace-Id')
118
trace_header = None
119
if trace_header_str:
120
trace_header = TraceHeader.from_header_str(trace_header_str)
121
122
# Create segment with trace context
123
with xray_recorder.in_segment('web-request') as segment:
124
# Add HTTP request metadata
125
segment.put_http_meta('url', request.url)
126
segment.put_http_meta('method', request.method)
127
segment.put_http_meta('user_agent', request.headers.get('User-Agent'))
128
segment.put_http_meta('client_ip', request.remote_addr)
129
130
# Set user if authenticated
131
if request.user:
132
segment.set_user(request.user.id)
133
134
# Process request
135
response = process_request(request)
136
137
# Add HTTP response metadata
138
segment.put_http_meta('response', {
139
'status': response.status_code
140
})
141
segment.apply_status_code(response.status_code)
142
143
return response
144
```
145
146
#### Outgoing HTTP Requests
147
148
Add trace headers to outgoing HTTP requests:
149
150
```python
151
import requests
152
from aws_xray_sdk.core import xray_recorder
153
154
def make_api_call(url):
155
with xray_recorder.in_subsegment('api-call') as subsegment:
156
# Get current trace context
157
trace_entity = xray_recorder.get_trace_entity()
158
159
# Create trace header for outgoing request
160
trace_header = TraceHeader(
161
root=trace_entity.trace_id,
162
parent=trace_entity.id,
163
sampled=1 if trace_entity.sampled else 0
164
)
165
166
# Add trace header to outgoing request
167
headers = {
168
'X-Amzn-Trace-Id': trace_header.to_header_str()
169
}
170
171
# Make request with tracing
172
subsegment.put_http_meta('url', url)
173
subsegment.put_http_meta('method', 'GET')
174
175
response = requests.get(url, headers=headers)
176
177
subsegment.put_http_meta('response', {
178
'status': response.status_code
179
})
180
subsegment.apply_status_code(response.status_code)
181
182
return response
183
```
184
185
#### Error Handling with HTTP Status
186
187
Automatic error flagging based on HTTP status codes:
188
189
```python
190
from aws_xray_sdk.core import xray_recorder
191
192
def api_endpoint():
193
with xray_recorder.in_segment('api-endpoint') as segment:
194
try:
195
result = process_api_request()
196
segment.apply_status_code(200)
197
return result, 200
198
except ValidationError:
199
segment.apply_status_code(400) # Sets error flag
200
return {'error': 'Invalid input'}, 400
201
except Exception as e:
202
segment.apply_status_code(500) # Sets fault flag
203
segment.add_exception(e)
204
return {'error': 'Internal error'}, 500
205
```
206
207
### HTTP Metadata Standard Keys
208
209
Common HTTP metadata keys used by X-Ray console and AWS services:
210
211
**Request Metadata:**
212
- `url`: Full request URL
213
- `method`: HTTP method
214
- `user_agent`: User-Agent header
215
- `client_ip`: Client IP address
216
- `x_forwarded_for`: X-Forwarded-For header
217
218
**Response Metadata:**
219
- `status`: HTTP status code
220
- `content_length`: Response content length
221
222
**Error Handling:**
223
Status codes automatically set trace flags:
224
- `4xx`: Error flag (client errors)
225
- `5xx`: Fault flag (server errors)
226
- `429`: Throttle flag (rate limiting)
227
228
### Integration with Web Frameworks
229
230
The HTTP utilities integrate seamlessly with X-Ray middleware for popular frameworks:
231
- Django: Automatic HTTP metadata collection
232
- Flask: Request/response tracing
233
- aiohttp: Async HTTP tracing
234
- Bottle: WSGI-compatible tracing