0
# Service Operations
1
2
Service metadata and discovery operations that provide information about available API operations and service capabilities. These operations enable applications to discover and understand the full capabilities of the Azure Subscription Management service.
3
4
## Capabilities
5
6
### List Available API Operations
7
8
Lists all available Microsoft.Subscription API operations, providing metadata about each operation including names, descriptions, and capabilities.
9
10
```python { .api }
11
def list(**kwargs) -> Iterable[Operation]:
12
"""
13
Lists all of the available Microsoft.Subscription API operations.
14
15
Returns:
16
Iterable[Operation]: Paginated list of available API operations
17
"""
18
```
19
20
**Usage Example:**
21
22
```python
23
from azure.identity import DefaultAzureCredential
24
from azure.mgmt.subscription import SubscriptionClient
25
26
credential = DefaultAzureCredential()
27
client = SubscriptionClient(credential)
28
29
try:
30
operations = list(client.operations.list())
31
32
print(f"Found {len(operations)} available operations:")
33
34
# Group operations by resource type
35
operation_groups = {}
36
37
for operation in operations:
38
# Extract resource type from operation name
39
parts = operation.name.split('/')
40
if len(parts) >= 2:
41
resource_type = parts[1]
42
if resource_type not in operation_groups:
43
operation_groups[resource_type] = []
44
operation_groups[resource_type].append(operation)
45
46
# Display operations by group
47
for resource_type, ops in operation_groups.items():
48
print(f"\n{resource_type.upper()} Operations:")
49
for op in ops:
50
display = op.display
51
if display:
52
print(f" {op.name}")
53
print(f" Description: {display.description}")
54
print(f" Provider: {display.provider}")
55
print(f" Resource: {display.resource}")
56
print(f" Operation: {display.operation}")
57
print(f" Data Action: {op.is_data_action}")
58
print(" ---")
59
60
except Exception as e:
61
print(f"Failed to list operations: {e}")
62
```
63
64
## Advanced Usage Patterns
65
66
### Operation Discovery and Validation
67
68
```python
69
def discover_subscription_capabilities(client):
70
"""Discover and categorize subscription management capabilities."""
71
72
try:
73
operations = list(client.operations.list())
74
75
capabilities = {
76
"subscription_management": [],
77
"tenant_operations": [],
78
"alias_operations": [],
79
"policy_operations": [],
80
"billing_operations": [],
81
"other": []
82
}
83
84
for operation in operations:
85
name_lower = operation.name.lower()
86
87
if "subscription" in name_lower and ("read" in name_lower or "list" in name_lower):
88
capabilities["subscription_management"].append(operation)
89
elif "tenant" in name_lower:
90
capabilities["tenant_operations"].append(operation)
91
elif "alias" in name_lower:
92
capabilities["alias_operations"].append(operation)
93
elif "policy" in name_lower or "policies" in name_lower:
94
capabilities["policy_operations"].append(operation)
95
elif "billing" in name_lower:
96
capabilities["billing_operations"].append(operation)
97
else:
98
capabilities["other"].append(operation)
99
100
# Display capabilities summary
101
print("Azure Subscription Management Capabilities:")
102
for category, ops in capabilities.items():
103
if ops:
104
print(f"\n{category.replace('_', ' ').title()}: {len(ops)} operations")
105
for op in ops[:3]: # Show first 3 operations as examples
106
if op.display:
107
print(f" - {op.display.operation}: {op.display.description}")
108
if len(ops) > 3:
109
print(f" ... and {len(ops) - 3} more")
110
111
return capabilities
112
113
except Exception as e:
114
print(f"Failed to discover capabilities: {e}")
115
return {}
116
```
117
118
### API Coverage Validation
119
120
```python
121
def validate_api_coverage(client, expected_operations):
122
"""Validate that expected operations are available in the API."""
123
124
try:
125
available_operations = list(client.operations.list())
126
available_names = {op.name for op in available_operations}
127
128
validation_results = {}
129
130
for expected_op in expected_operations:
131
if expected_op in available_names:
132
validation_results[expected_op] = "Available"
133
else:
134
validation_results[expected_op] = "Missing"
135
136
# Find unexpected operations
137
expected_set = set(expected_operations)
138
unexpected = available_names - expected_set
139
140
print("API Coverage Validation Results:")
141
print(f"Expected Operations: {len(expected_operations)}")
142
print(f"Available Operations: {len(available_operations)}")
143
print(f"Missing Operations: {sum(1 for v in validation_results.values() if v == 'Missing')}")
144
print(f"Unexpected Operations: {len(unexpected)}")
145
146
# Show missing operations
147
missing = [op for op, status in validation_results.items() if status == "Missing"]
148
if missing:
149
print("\nMissing Operations:")
150
for op in missing:
151
print(f" - {op}")
152
153
# Show some unexpected operations
154
if unexpected:
155
print(f"\nUnexpected Operations (showing first 5):")
156
for op in list(unexpected)[:5]:
157
print(f" - {op}")
158
159
return validation_results
160
161
except Exception as e:
162
print(f"Failed to validate API coverage: {e}")
163
return {}
164
165
# Example usage
166
expected_ops = [
167
"Microsoft.Subscription/subscriptions/read",
168
"Microsoft.Subscription/subscriptions/locations/read",
169
"Microsoft.Subscription/tenants/read",
170
"Microsoft.Subscription/aliases/write",
171
"Microsoft.Subscription/aliases/read",
172
"Microsoft.Subscription/aliases/delete"
173
]
174
175
validation = validate_api_coverage(client, expected_ops)
176
```
177
178
### Operation Metadata Analysis
179
180
```python
181
def analyze_operation_metadata(client):
182
"""Analyze operation metadata for insights about the API."""
183
184
try:
185
operations = list(client.operations.list())
186
187
analysis = {
188
"total_operations": len(operations),
189
"data_actions": 0,
190
"management_actions": 0,
191
"providers": set(),
192
"resources": set(),
193
"operation_types": {}
194
}
195
196
for operation in operations:
197
# Count data vs management actions
198
if operation.is_data_action:
199
analysis["data_actions"] += 1
200
else:
201
analysis["management_actions"] += 1
202
203
# Analyze display information
204
if operation.display:
205
display = operation.display
206
analysis["providers"].add(display.provider)
207
analysis["resources"].add(display.resource)
208
209
# Categorize operation types
210
op_type = display.operation.lower()
211
if "read" in op_type or "list" in op_type or "get" in op_type:
212
category = "Read"
213
elif "write" in op_type or "create" in op_type or "put" in op_type:
214
category = "Write"
215
elif "delete" in op_type:
216
category = "Delete"
217
else:
218
category = "Other"
219
220
analysis["operation_types"][category] = analysis["operation_types"].get(category, 0) + 1
221
222
# Display analysis
223
print("Operation Metadata Analysis:")
224
print(f"Total Operations: {analysis['total_operations']}")
225
print(f"Data Actions: {analysis['data_actions']}")
226
print(f"Management Actions: {analysis['management_actions']}")
227
print(f"Unique Providers: {len(analysis['providers'])}")
228
print(f"Unique Resources: {len(analysis['resources'])}")
229
230
print("\nOperation Types:")
231
for op_type, count in analysis["operation_types"].items():
232
percentage = (count / analysis["total_operations"]) * 100
233
print(f" {op_type}: {count} ({percentage:.1f}%)")
234
235
print("\nProviders:")
236
for provider in sorted(analysis["providers"]):
237
print(f" - {provider}")
238
239
print("\nResource Types:")
240
for resource in sorted(analysis["resources"]):
241
print(f" - {resource}")
242
243
return analysis
244
245
except Exception as e:
246
print(f"Failed to analyze operation metadata: {e}")
247
return {}
248
```
249
250
## Error Handling
251
252
```python
253
from azure.core.exceptions import HttpResponseError
254
255
def handle_operations_errors(func, *args, **kwargs):
256
"""Error handler for operations listing."""
257
try:
258
return func(*args, **kwargs)
259
except HttpResponseError as e:
260
if e.status_code == 403:
261
print("Insufficient permissions to list operations")
262
elif e.status_code == 401:
263
print("Authentication failed - check credentials")
264
else:
265
print(f"Error listing operations: {e.status_code} - {e.message}")
266
raise
267
except Exception as e:
268
print(f"Unexpected error listing operations: {e}")
269
raise
270
271
# Example usage
272
try:
273
operations = handle_operations_errors(client.operations.list)
274
operations_list = list(operations)
275
print(f"Successfully retrieved {len(operations_list)} operations")
276
except Exception:
277
print("Failed to retrieve operations list")
278
```
279
280
## Integration with Other Capabilities
281
282
### Dynamic Client Capability Detection
283
284
```python
285
def detect_client_capabilities(client):
286
"""Detect what capabilities are available in the current client."""
287
288
available_capabilities = {
289
"subscription_management": False,
290
"tenant_discovery": False,
291
"subscription_lifecycle": False,
292
"alias_management": False,
293
"policy_management": False,
294
"billing_account_access": False
295
}
296
297
try:
298
operations = list(client.operations.list())
299
300
for operation in operations:
301
name = operation.name.lower()
302
303
if "subscriptions/read" in name or "subscriptions/locations" in name:
304
available_capabilities["subscription_management"] = True
305
elif "tenants/read" in name:
306
available_capabilities["tenant_discovery"] = True
307
elif "subscriptions/cancel" in name or "subscriptions/rename" in name:
308
available_capabilities["subscription_lifecycle"] = True
309
elif "aliases" in name:
310
available_capabilities["alias_management"] = True
311
elif "policies" in name or "policy" in name:
312
available_capabilities["policy_management"] = True
313
elif "billingaccount" in name:
314
available_capabilities["billing_account_access"] = True
315
316
print("Detected Client Capabilities:")
317
for capability, available in available_capabilities.items():
318
status = "✓" if available else "✗"
319
print(f" {status} {capability.replace('_', ' ').title()}")
320
321
return available_capabilities
322
323
except Exception as e:
324
print(f"Failed to detect capabilities: {e}")
325
return available_capabilities
326
```
327
328
## Types
329
330
```python { .api }
331
class Operation:
332
"""Information about an API operation."""
333
name: str # Operation name (e.g., "Microsoft.Subscription/subscriptions/read")
334
is_data_action: bool # Whether this is a data action (vs management action)
335
display: OperationDisplay # Display information for the operation
336
origin: str # Origin of the operation
337
action_type: str # Type of action
338
339
class OperationDisplay:
340
"""Display information for an API operation."""
341
provider: str # Resource provider name (e.g., "Microsoft Subscription")
342
resource: str # Resource type (e.g., "Subscription")
343
operation: str # Operation name (e.g., "Get subscription")
344
description: str # Human-readable description of the operation
345
346
class OperationListResult:
347
"""Result of listing operations."""
348
value: List[Operation] # List of operations
349
next_link: str # URL for next page of results (optional)
350
```
351
352
## Usage in Application Development
353
354
Service operations are particularly useful for:
355
356
1. **API Discovery**: Understanding what operations are available
357
2. **Documentation Generation**: Automatically generating API documentation
358
3. **Client Validation**: Ensuring expected operations are available
359
4. **Feature Detection**: Determining what capabilities are supported
360
5. **Monitoring**: Tracking API changes and new features
361
6. **Testing**: Validating API coverage in test suites