0
# HTTP Operations
1
2
Comprehensive HTTP method support for RESTful operations. RestNavigator provides methods for all standard HTTP verbs with proper error handling, response management, and HAL-specific processing.
3
4
## Capabilities
5
6
### Resource Creation (POST)
7
8
Create new resources using POST requests with automatic response handling and navigation.
9
10
```python { .api }
11
class HALNavigator:
12
def create(self, body: dict = None, raise_exc: bool = True, headers: dict = None) -> 'OrphanHALNavigator':
13
"""
14
POST request to create a new resource.
15
16
Parameters:
17
- body: Request body data (will be JSON-encoded)
18
- raise_exc: Whether to raise exceptions on HTTP errors
19
- headers: Additional headers for this request
20
21
Returns:
22
OrphanHALNavigator containing response data
23
"""
24
```
25
26
Usage example:
27
28
```python
29
# Create a new user
30
new_user = api['users'].create({
31
'username': 'john_doe',
32
'email': 'john@example.com',
33
'full_name': 'John Doe'
34
})
35
36
# Check the response status
37
if new_user: # Truthy if HTTP 2xx status
38
print("User created successfully")
39
print("Response data:", new_user.state)
40
print("Status:", new_user.status)
41
42
# Handle errors gracefully
43
result = api['users'].create({'invalid': 'data'}, raise_exc=False)
44
if not result:
45
print("Creation failed:", result.status)
46
print("Error details:", result.state)
47
```
48
49
### Resource Replacement (PUT)
50
51
Replace entire resources using PUT requests for idempotent create-or-update operations.
52
53
```python { .api }
54
class HALNavigator:
55
def upsert(self, body: dict, raise_exc: bool = True, headers = False) -> 'OrphanHALNavigator':
56
"""
57
PUT request for idempotent create/update operations.
58
59
Parameters:
60
- body: Complete resource representation
61
- raise_exc: Whether to raise exceptions on HTTP errors
62
- headers: Additional headers for this request
63
64
Returns:
65
OrphanHALNavigator containing response data
66
"""
67
```
68
69
Usage example:
70
71
```python
72
# Replace entire user resource
73
updated_user = user.upsert({
74
'id': 123,
75
'username': 'john_doe',
76
'email': 'john.doe@newdomain.com',
77
'full_name': 'John David Doe',
78
'status': 'active'
79
})
80
81
# PUT is idempotent - can be called multiple times
82
user.upsert(complete_user_data)
83
```
84
85
### Partial Updates (PATCH)
86
87
Update specific fields of resources using PATCH requests for partial modifications.
88
89
```python { .api }
90
class HALNavigator:
91
def patch(self, body: dict, raise_exc: bool = True, headers = False) -> 'OrphanHALNavigator':
92
"""
93
PATCH request for partial resource updates.
94
95
Parameters:
96
- body: Partial resource data to update
97
- raise_exc: Whether to raise exceptions on HTTP errors
98
- headers: Additional headers for this request
99
100
Returns:
101
OrphanHALNavigator containing response data
102
"""
103
```
104
105
Usage example:
106
107
```python
108
# Update only specific fields
109
result = user.patch({
110
'email': 'newemail@example.com',
111
'last_login': '2023-01-15T10:30:00Z'
112
})
113
114
# Update with custom headers
115
result = user.patch(
116
{'status': 'inactive'},
117
headers={'X-Admin-Override': 'true'}
118
)
119
```
120
121
### Resource Deletion (DELETE)
122
123
Remove resources using DELETE requests with proper response handling.
124
125
```python { .api }
126
class HALNavigator:
127
def delete(self, raise_exc: bool = True, headers: dict = None) -> 'OrphanHALNavigator':
128
"""
129
DELETE request to remove the resource.
130
131
Parameters:
132
- raise_exc: Whether to raise exceptions on HTTP errors
133
- headers: Additional headers for this request
134
135
Returns:
136
OrphanHALNavigator containing response data
137
"""
138
```
139
140
Usage example:
141
142
```python
143
# Delete a resource
144
result = user.delete()
145
146
# Check if deletion was successful
147
if result:
148
print("User deleted successfully")
149
150
# Delete with custom headers
151
admin_user.delete(headers={'X-Force-Delete': 'true'})
152
153
# Handle deletion errors
154
result = user.delete(raise_exc=False)
155
if result.status[0] == 404:
156
print("User was already deleted")
157
elif result.status[0] >= 400:
158
print("Deletion failed:", result.state)
159
```
160
161
### Response Handling
162
163
All HTTP operations return `OrphanHALNavigator` instances that provide access to response data and status information.
164
165
```python { .api }
166
class OrphanHALNavigator(HALNavigator):
167
def __call__(self) -> dict:
168
"""
169
Return response state (cannot fetch from server).
170
171
Returns:
172
Response data as dictionary
173
"""
174
175
@property
176
def parent(self) -> 'HALNavigator':
177
"""Reference to the navigator this was created from"""
178
```
179
180
### Error Handling Patterns
181
182
```python
183
# Automatic exception raising (default)
184
try:
185
result = api['users'].create(user_data)
186
print("Success:", result.state)
187
except HALNavigatorError as e:
188
print(f"HTTP {e.status}: {e.message}")
189
print("Response:", e.response.text)
190
191
# Manual error checking
192
result = api['users'].create(user_data, raise_exc=False)
193
if result: # Check boolean status
194
print("Success:", result.state)
195
else:
196
status_code, reason = result.status
197
print(f"Failed: {status_code} {reason}")
198
print("Error details:", result.state)
199
200
# Status code specific handling
201
result = user.delete(raise_exc=False)
202
if result.status[0] == 204:
203
print("Deleted successfully (no content)")
204
elif result.status[0] == 404:
205
print("Resource not found")
206
elif result.status[0] >= 400:
207
print("Deletion failed:", result.state)
208
```
209
210
### Content Type and Headers
211
212
```python
213
# Custom content type
214
result = api['documents'].create(
215
{'content': 'Document text'},
216
headers={'Content-Type': 'application/vnd.api+json'}
217
)
218
219
# Working with different response formats
220
result = api['export'].create({'format': 'csv'})
221
if result.response.headers.get('content-type') == 'text/csv':
222
csv_data = result.response.text
223
```