0
# Client Management
1
2
Core functionality for creating and managing Swagger clients from OpenAPI specifications. This module provides the main entry point to bravado through the SwaggerClient class, which dynamically generates API methods from OpenAPI/Swagger specifications.
3
4
## Capabilities
5
6
### SwaggerClient
7
8
The main client class that provides an interface for making API calls based on a Swagger spec. It dynamically creates resource objects and operations from the specification.
9
10
```python { .api }
11
class SwaggerClient:
12
def __init__(self, swagger_spec, also_return_response: bool = False): ...
13
@classmethod
14
def from_url(cls, spec_url: str, http_client=None, request_headers: dict = None, config: dict = None) -> 'SwaggerClient': ...
15
@classmethod
16
def from_spec(cls, spec_dict: dict, origin_url: str = None, http_client=None, config: dict = None) -> 'SwaggerClient': ...
17
def get_model(self, model_name: str): ...
18
def is_equal(self, other: 'SwaggerClient') -> bool: ...
19
def __deepcopy__(self, memo=None) -> 'SwaggerClient': ...
20
def __repr__(self) -> str: ...
21
```
22
23
**Parameters:**
24
- `swagger_spec`: bravado_core.spec.Spec object containing the parsed OpenAPI specification
25
- `also_return_response` (bool): If True, operations return both result and response metadata
26
- `spec_url` (str): URL pointing to the OpenAPI specification
27
- `http_client`: HTTP client instance (defaults to RequestsClient)
28
- `request_headers` (dict): Headers to include with HTTP requests
29
- `config` (dict): Configuration dictionary for bravado and bravado_core
30
- `spec_dict` (dict): OpenAPI specification as a dictionary
31
- `origin_url` (str): Base URL for resolving relative references
32
- `model_name` (str): Name of the model to retrieve
33
34
**Returns:**
35
- `from_url`/`from_spec`: SwaggerClient instance
36
- `get_model`: Model class for the specified model name
37
- `is_equal`: Boolean indicating if clients are equivalent
38
39
**Usage Example:**
40
41
```python
42
from bravado.client import SwaggerClient
43
44
# Create client from URL
45
client = SwaggerClient.from_url('http://petstore.swagger.io/v2/swagger.json')
46
47
# Access API resources dynamically
48
pet_store = client.pet
49
pet = pet_store.getPetById(petId=1).response().result
50
51
# Create client from spec dict
52
import requests
53
spec_dict = requests.get('http://petstore.swagger.io/v2/swagger.json').json()
54
client = SwaggerClient.from_spec(spec_dict)
55
56
# Get model definitions
57
Pet = client.get_model('Pet')
58
new_pet = Pet(name='Fluffy', photoUrls=['http://example.com/fluffy.jpg'])
59
```
60
61
### ResourceDecorator
62
63
Wraps bravado_core.Resource objects to provide dynamic operation access with consistent response handling.
64
65
```python { .api }
66
class ResourceDecorator:
67
def __init__(self, resource, also_return_response: bool = False): ...
68
```
69
70
**Parameters:**
71
- `resource`: bravado_core.resource.Resource object
72
- `also_return_response` (bool): Whether to return response metadata
73
74
### CallableOperation
75
76
Makes operations callable and provides dynamic docstrings. Handles parameter validation, request construction, and returns HttpFuture objects.
77
78
```python { .api }
79
class CallableOperation:
80
def __init__(self, operation, also_return_response: bool = False): ...
81
def __call__(self, **op_kwargs) -> HttpFuture: ...
82
```
83
84
**Parameters:**
85
- `operation`: bravado_core.operation.Operation object
86
- `also_return_response` (bool): Whether to return response metadata
87
- `**op_kwargs`: Operation parameters as defined in the OpenAPI spec
88
89
**Returns:**
90
- HttpFuture object that can be used to get the response
91
92
**Usage Example:**
93
94
```python
95
# Operations are called with parameters matching the OpenAPI spec
96
future = client.pet.getPetById(petId=42)
97
98
# Get the response (blocks until complete)
99
response = future.response()
100
pet_data = response.result
101
status_code = response.metadata.status_code
102
```
103
104
### Utility Functions
105
106
Helper functions for request construction and parameter handling.
107
108
```python { .api }
109
def inject_headers_for_remote_refs(request_callable, request_headers: dict): ...
110
def construct_request(operation, request_options: dict, **op_kwargs) -> dict: ...
111
def construct_params(operation, request: dict, op_kwargs: dict): ...
112
```
113
114
**Parameters:**
115
- `request_callable`: Function that makes HTTP requests
116
- `request_headers` (dict): Headers to inject for remote reference requests
117
- `operation`: bravado_core.operation.Operation object
118
- `request_options` (dict): HTTP request configuration
119
- `request` (dict): Request dictionary being constructed
120
- `op_kwargs` (dict): Operation parameters
121
122
**Returns:**
123
- `inject_headers_for_remote_refs`: Modified request callable with injected headers
124
- `construct_request`: Complete request dictionary ready for HTTP client
125
- `construct_params`: Validated and marshalled parameters
126
127
## Configuration
128
129
Client behavior can be customized through the config parameter:
130
131
```python
132
config = {
133
'also_return_response': True, # Return response metadata with results
134
'validate_requests': True, # Validate request parameters
135
'validate_responses': True, # Validate response data
136
'use_models': True, # Use model objects for complex types
137
}
138
139
client = SwaggerClient.from_url(spec_url, config=config)
140
```
141
142
## Error Handling
143
144
SwaggerClient operations can raise various exceptions:
145
146
- **SwaggerMappingError**: Invalid operation parameters or missing required fields
147
- **HTTPError**: HTTP-level errors (4xx, 5xx status codes)
148
- **BravadoTimeoutError**: Request timeouts
149
- **BravadoConnectionError**: Connection failures
150
151
```python
152
from bravado.exception import HTTPNotFound, BravadoTimeoutError
153
154
try:
155
pet = client.pet.getPetById(petId=999).response().result
156
except HTTPNotFound:
157
print("Pet not found")
158
except BravadoTimeoutError:
159
print("Request timed out")
160
```