-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutility-functions.ps1
More file actions
587 lines (473 loc) · 18.7 KB
/
utility-functions.ps1
File metadata and controls
587 lines (473 loc) · 18.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
# API Utility Functions
# Reusable functions for common API operations
#
# WHAT YOU CAN MODIFY:
# - Function parameters: Add/remove parameters based on your needs
# - Default values: Adjust timeouts, retry counts, etc.
# - Response processing: Change how responses are handled
# - Validation logic: Add checks specific to your APIs
#
# WHAT YOU SHOULDN'T CHANGE:
# - Core function structure and error handling
# - Parameter validation patterns
# - Try/catch blocks and exception handling
# - The fundamental API calling mechanisms
#
# HOW TO USE THESE FUNCTIONS:
# 1. Copy the functions you need into your scripts
# 2. Modify parameters and defaults for your use case
# 3. Add your API-specific logic where indicated
# 4. Use these as building blocks for more complex operations
Write-Host "=== API Utility Functions ===" -ForegroundColor Green
# Function 1: Generic API caller with comprehensive options
# MODIFY: Add parameters your APIs commonly need
# DON'T CHANGE: The core error handling and structure
function Invoke-ApiCall {
<#
.SYNOPSIS
Makes HTTP requests to APIs with comprehensive error handling and retry logic
.PARAMETER Uri
The API endpoint URL
.PARAMETER Method
HTTP method (GET, POST, PUT, DELETE, etc.)
.PARAMETER Headers
Hashtable of HTTP headers
.PARAMETER Body
Request body (will be converted to JSON if it's an object)
.PARAMETER TimeoutSec
Request timeout in seconds
.PARAMETER MaxRetries
Maximum number of retry attempts
.PARAMETER RetryDelay
Base delay between retries (uses exponential backoff)
#>
param(
[Parameter(Mandatory = $true)]
[string]$Uri,
[Parameter(Mandatory = $false)]
[string]$Method = "GET",
[Parameter(Mandatory = $false)]
[hashtable]$Headers = @{},
[Parameter(Mandatory = $false)]
$Body = $null,
[Parameter(Mandatory = $false)]
[int]$TimeoutSec = 30, # MODIFY: Adjust default timeout
[Parameter(Mandatory = $false)]
[int]$MaxRetries = 3, # MODIFY: Adjust default retry count
[Parameter(Mandatory = $false)]
[int]$RetryDelay = 1 # MODIFY: Adjust base retry delay
)
# MODIFY: Add any default headers your APIs need
if (-not $Headers.ContainsKey("User-Agent")) {
$Headers["User-Agent"] = "PowerShell-API-Client/1.0" # Change to your app name
}
# DON'T CHANGE: This handles JSON conversion properly
if ($Body -and $Body -isnot [string]) {
$Body = $Body | ConvertTo-Json -Depth 10
if (-not $Headers.ContainsKey("Content-Type")) {
$Headers["Content-Type"] = "application/json"
}
}
for ($attempt = 1; $attempt -le $MaxRetries; $attempt++) {
try {
Write-Verbose "Attempt $attempt/$MaxRetries to $Method $Uri"
# MODIFY: Add any pre-request logic here
$params = @{
Uri = $Uri
Method = $Method
Headers = $Headers
TimeoutSec = $TimeoutSec
ErrorAction = "Stop"
}
if ($Body) {
$params.Body = $Body
}
$response = Invoke-RestMethod @params
# MODIFY: Add any post-request processing here
Write-Verbose "Request successful on attempt $attempt"
return $response
} catch [System.Net.WebException] {
$statusCode = [int]$_.Exception.Response.StatusCode
# MODIFY: Customize which errors should trigger retries
$retryableErrors = @(429, 500, 502, 503, 504)
if ($statusCode -in $retryableErrors -and $attempt -lt $MaxRetries) {
$delay = $RetryDelay * [Math]::Pow(2, $attempt - 1)
Write-Warning "HTTP $statusCode - Retrying in $delay seconds (attempt $attempt/$MaxRetries)"
Start-Sleep -Seconds $delay
} else {
Write-Error "HTTP $statusCode - $($_.Exception.Message)"
throw
}
} catch {
Write-Error "Request failed: $($_.Exception.Message)"
throw
}
}
throw "Maximum retry attempts ($MaxRetries) exceeded"
}
# Function 2: Authenticated API helper
# MODIFY: Adjust for your authentication method
function Invoke-AuthenticatedApi {
<#
.SYNOPSIS
Makes authenticated API calls with automatic token handling
.PARAMETER Uri
The API endpoint URL
.PARAMETER Token
Bearer token for authentication
.PARAMETER Method
HTTP method
.PARAMETER Body
Request body
.PARAMETER ApiKeyHeader
Header name for API key authentication (alternative to Bearer)
#>
param(
[Parameter(Mandatory = $true)]
[string]$Uri,
[Parameter(Mandatory = $false)]
[string]$Token = $env:API_TOKEN, # MODIFY: Change default token source
[Parameter(Mandatory = $false)]
[string]$Method = "GET",
[Parameter(Mandatory = $false)]
$Body = $null,
[Parameter(Mandatory = $false)]
[string]$ApiKeyHeader = $null # MODIFY: Set default API key header name
)
if (-not $Token) {
throw "No authentication token provided. Set `$env:API_TOKEN or pass -Token parameter"
}
$headers = @{
"Accept" = "application/json"
# MODIFY: Change this based on your API's authentication method
}
# MODIFY: Adjust authentication header format for your API
if ($ApiKeyHeader) {
$headers[$ApiKeyHeader] = $Token
} else {
$headers["Authorization"] = "Bearer $Token" # Most common format
}
try {
return Invoke-ApiCall -Uri $Uri -Method $Method -Headers $headers -Body $Body
} catch [System.Net.WebException] {
$statusCode = [int]$_.Exception.Response.StatusCode
if ($statusCode -eq 401) {
throw "Authentication failed - check your API token"
} elseif ($statusCode -eq 403) {
throw "Access forbidden - token may lack required permissions"
} else {
throw
}
}
}
# Function 3: API response validator
# MODIFY: Add validation rules specific to your APIs
function Test-ApiResponse {
<#
.SYNOPSIS
Validates API responses against expected patterns
.PARAMETER Response
The API response object to validate
.PARAMETER RequiredFields
Array of field names that must be present
.PARAMETER ValidateJson
Whether to validate JSON structure
#>
param(
[Parameter(Mandatory = $true)]
$Response,
[Parameter(Mandatory = $false)]
[string[]]$RequiredFields = @(), # MODIFY: Add your required fields
[Parameter(Mandatory = $false)]
[switch]$ValidateJson
)
$validationErrors = @()
# MODIFY: Add your specific validation logic
if ($ValidateJson -and $Response -is [string]) {
try {
$Response | ConvertFrom-Json | Out-Null
} catch {
$validationErrors += "Invalid JSON format"
}
}
# Check required fields
foreach ($field in $RequiredFields) {
if (-not ($Response.PSObject.Properties.Name -contains $field)) {
$validationErrors += "Missing required field: $field"
}
}
# MODIFY: Add more validation rules as needed
# Example: Check data types, value ranges, etc.
if ($validationErrors.Count -gt 0) {
throw "Response validation failed: $($validationErrors -join ', ')"
}
return $true
}
# Function 4: Batch API operations
# MODIFY: Adjust for your batch processing needs
function Invoke-ApiBatch {
<#
.SYNOPSIS
Processes multiple API requests with rate limiting and error handling
.PARAMETER Requests
Array of hashtables containing request parameters
.PARAMETER DelayMs
Delay between requests in milliseconds
.PARAMETER StopOnError
Whether to stop processing on first error
#>
param(
[Parameter(Mandatory = $true)]
[hashtable[]]$Requests,
[Parameter(Mandatory = $false)]
[int]$DelayMs = 500, # MODIFY: Adjust rate limiting delay
[Parameter(Mandatory = $false)]
[switch]$StopOnError = $false
)
$results = @()
$successCount = 0
$errorCount = 0
for ($i = 0; $i -lt $Requests.Count; $i++) {
$request = $Requests[$i]
Write-Progress -Activity "Processing API Requests" -Status "Request $($i+1) of $($Requests.Count)" -PercentComplete (($i / $Requests.Count) * 100)
try {
# MODIFY: Adjust required parameters for your requests
$result = Invoke-ApiCall @request
$results += @{
Index = $i
Success = $true
Response = $result
Error = $null
}
$successCount++
} catch {
$results += @{
Index = $i
Success = $false
Response = $null
Error = $_.Exception.Message
}
$errorCount++
if ($StopOnError) {
Write-Error "Stopping batch processing due to error: $($_.Exception.Message)"
break
}
}
# Rate limiting delay
if ($i -lt ($Requests.Count - 1)) {
Start-Sleep -Milliseconds $DelayMs
}
}
Write-Progress -Activity "Processing API Requests" -Completed
Write-Host "Batch processing complete: $successCount successful, $errorCount failed" -ForegroundColor Cyan
return $results
}
# Function 5: API health checker
# MODIFY: Adjust health check criteria for your APIs
function Test-ApiHealth {
<#
.SYNOPSIS
Checks API health and response times
.PARAMETER BaseUri
Base URL of the API to test
.PARAMETER HealthEndpoint
Health check endpoint path
.PARAMETER MaxResponseTime
Maximum acceptable response time in milliseconds
#>
param(
[Parameter(Mandatory = $true)]
[string]$BaseUri,
[Parameter(Mandatory = $false)]
[string]$HealthEndpoint = "/health", # MODIFY: Change default health endpoint
[Parameter(Mandatory = $false)]
[int]$MaxResponseTime = 5000 # MODIFY: Adjust acceptable response time
)
$healthUrl = "$BaseUri$HealthEndpoint".TrimEnd('/')
$stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
try {
Write-Host "Checking API health: $healthUrl" -ForegroundColor Cyan
$response = Invoke-RestMethod -Uri $healthUrl -Method GET -TimeoutSec 10
$stopwatch.Stop()
$responseTime = $stopwatch.ElapsedMilliseconds
# MODIFY: Adjust health check criteria
$healthStatus = @{
Healthy = $true
ResponseTime = $responseTime
Status = "OK"
Timestamp = Get-Date
}
if ($responseTime -gt $MaxResponseTime) {
$healthStatus.Healthy = $false
$healthStatus.Status = "SLOW - Response time exceeds threshold"
}
# MODIFY: Add more health checks based on response content
# Example: Check for specific fields in the response
Write-Host "✅ API Health: $($healthStatus.Status) ($($responseTime)ms)" -ForegroundColor Green
return $healthStatus
} catch {
$stopwatch.Stop()
$healthStatus = @{
Healthy = $false
ResponseTime = $stopwatch.ElapsedMilliseconds
Status = "ERROR - $($_.Exception.Message)"
Timestamp = Get-Date
}
Write-Host "❌ API Health: $($healthStatus.Status)" -ForegroundColor Red
return $healthStatus
}
}
# Function 6: API configuration helper
# MODIFY: Adjust for your API's configuration needs
function New-ApiConfig {
<#
.SYNOPSIS
Creates a standardized API configuration object
.PARAMETER BaseUrl
Base URL of the API
.PARAMETER ApiKey
API key for authentication
.PARAMETER Version
API version
.PARAMETER Timeout
Default timeout for requests
#>
param(
[Parameter(Mandatory = $true)]
[string]$BaseUrl,
[Parameter(Mandatory = $false)]
[string]$ApiKey = $env:API_KEY,
[Parameter(Mandatory = $false)]
[string]$Version = "v1", # MODIFY: Set your default API version
[Parameter(Mandatory = $false)]
[int]$Timeout = 30 # MODIFY: Set your default timeout
)
# MODIFY: Add more configuration options as needed
return @{
BaseUrl = $BaseUrl.TrimEnd('/')
ApiKey = $ApiKey
Version = $Version
Timeout = $Timeout
Headers = @{
"Accept" = "application/json"
"User-Agent" = "PowerShell-API-Client/1.0" # MODIFY: Change to your app
}
# Add more default settings
}
}
# Function 7: API endpoint builder
# MODIFY: Adjust URL building logic for your API structure
function Build-ApiUrl {
<#
.SYNOPSIS
Builds API URLs with proper encoding and parameters
.PARAMETER Config
API configuration object from New-ApiConfig
.PARAMETER Endpoint
API endpoint path
.PARAMETER QueryParams
Hashtable of query parameters
#>
param(
[Parameter(Mandatory = $true)]
[hashtable]$Config,
[Parameter(Mandatory = $true)]
[string]$Endpoint,
[Parameter(Mandatory = $false)]
[hashtable]$QueryParams = @{}
)
# MODIFY: Adjust URL structure for your API
$url = "$($Config.BaseUrl)/$($Config.Version)/$($Endpoint.TrimStart('/'))"
if ($QueryParams.Count -gt 0) {
$queryString = ($QueryParams.GetEnumerator() | ForEach-Object {
"$([Uri]::EscapeDataString($_.Key))=$([Uri]::EscapeDataString($_.Value))"
}) -join "&"
$url += "?$queryString"
}
return $url
}
Write-Host "`n=== Example Usage of Utility Functions ===" -ForegroundColor Green
# Example 1: Using the generic API caller
Write-Host "`n1. Using Invoke-ApiCall:" -ForegroundColor Yellow
try {
$response = Invoke-ApiCall -Uri "https://httpbin.org/get" -Method "GET" -TimeoutSec 10
Write-Host "✅ Generic API call successful" -ForegroundColor Green
} catch {
Write-Host "❌ API call failed: $($_.Exception.Message)" -ForegroundColor Red
}
# Example 2: Using authenticated API helper
Write-Host "`n2. Using authenticated API (set \$env:API_TOKEN to test):" -ForegroundColor Yellow
if ($env:API_TOKEN) {
try {
$response = Invoke-AuthenticatedApi -Uri "https://httpbin.org/bearer" -Method "GET"
Write-Host "✅ Authenticated API call successful" -ForegroundColor Green
} catch {
Write-Host "❌ Authenticated call failed: $($_.Exception.Message)" -ForegroundColor Red
}
} else {
Write-Host "ℹ️ Set \$env:API_TOKEN to test authenticated calls" -ForegroundColor Blue
}
# Example 3: Using response validator
Write-Host "`n3. Using response validator:" -ForegroundColor Yellow
try {
$testResponse = @{ name = "test"; id = 123; status = "active" }
$isValid = Test-ApiResponse -Response $testResponse -RequiredFields @("name", "id")
Write-Host "✅ Response validation passed" -ForegroundColor Green
} catch {
Write-Host "❌ Response validation failed: $($_.Exception.Message)" -ForegroundColor Red
}
# Example 4: Using batch operations
Write-Host "`n4. Using batch API operations:" -ForegroundColor Yellow
$batchRequests = @(
@{ Uri = "https://httpbin.org/get"; Method = "GET" }
@{ Uri = "https://httpbin.org/user-agent"; Method = "GET" }
@{ Uri = "https://httpbin.org/headers"; Method = "GET" }
)
try {
$results = Invoke-ApiBatch -Requests $batchRequests -DelayMs 200
$successCount = ($results | Where-Object { $_.Success }).Count
Write-Host "✅ Batch completed: $successCount/$($results.Count) successful" -ForegroundColor Green
} catch {
Write-Host "❌ Batch operation failed: $($_.Exception.Message)" -ForegroundColor Red
}
# Example 5: Using health checker
Write-Host "`n5. Using API health checker:" -ForegroundColor Yellow
try {
$health = Test-ApiHealth -BaseUri "https://httpbin.org" -HealthEndpoint "/get" -MaxResponseTime 2000
if ($health.Healthy) {
Write-Host "✅ API is healthy" -ForegroundColor Green
} else {
Write-Host "⚠️ API health issues detected" -ForegroundColor Yellow
}
} catch {
Write-Host "❌ Health check failed: $($_.Exception.Message)" -ForegroundColor Red
}
# Example 6: Using configuration and URL builder
Write-Host "`n6. Using API configuration:" -ForegroundColor Yellow
try {
# MODIFY: Replace with your actual API details
$config = New-ApiConfig -BaseUrl "https://api.example.com" -Version "v2" -Timeout 15
$url = Build-ApiUrl -Config $config -Endpoint "users/123" -QueryParams @{ include = "profile"; format = "json" }
Write-Host "✅ Built URL: $url" -ForegroundColor Green
} catch {
Write-Host "❌ Configuration failed: $($_.Exception.Message)" -ForegroundColor Red
}
Write-Host "`n=== How to Use These Functions ===" -ForegroundColor Magenta
Write-Host "📋 COPY AND MODIFY:" -ForegroundColor Yellow
Write-Host " 1. Copy the functions you need into your scripts" -ForegroundColor White
Write-Host " 2. Modify parameters and defaults for your APIs" -ForegroundColor White
Write-Host " 3. Adjust authentication methods and headers" -ForegroundColor White
Write-Host " 4. Customize validation rules and error handling" -ForegroundColor White
Write-Host " 5. Add your API-specific logic where indicated" -ForegroundColor White
Write-Host "`n🔧 CUSTOMIZATION POINTS:" -ForegroundColor Yellow
Write-Host " • Default timeouts and retry counts" -ForegroundColor White
Write-Host " • Authentication header formats" -ForegroundColor White
Write-Host " • Response validation rules" -ForegroundColor White
Write-Host " • Error handling strategies" -ForegroundColor White
Write-Host " • Rate limiting delays" -ForegroundColor White
Write-Host " • Health check criteria" -ForegroundColor White
Write-Host "`n✅ KEEP UNCHANGED:" -ForegroundColor Green
Write-Host " • Core error handling patterns" -ForegroundColor White
Write-Host " • Try/catch block structures" -ForegroundColor White
Write-Host " • Parameter validation" -ForegroundColor White
Write-Host " • Exponential backoff algorithms" -ForegroundColor White