-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpost-requests.ps1
More file actions
299 lines (268 loc) · 11.7 KB
/
post-requests.ps1
File metadata and controls
299 lines (268 loc) · 11.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
# POST Request Examples
# Examples for sending data to APIs using POST requests
#
# WHAT YOU CAN MODIFY:
# - URLs: Replace with your actual API endpoints
# - Data structure: Change to match your API's expected format
# - Content-Type: Adjust based on your API requirements
# - Headers: Add authentication and required headers
#
# WHAT YOU SHOULDN'T CHANGE:
# - ConvertTo-Json usage for JSON APIs
# - Content-Type header setting
# - Error handling patterns
# - The basic POST structure
#
# SECURITY CONSIDERATIONS:
# - Validate all input data before sending
# - Use HTTPS for sensitive data
# - Include authentication headers when required
# - Be careful with file uploads and size limits
# - Never log sensitive POST data
Write-Host "=== POST Request Examples ===" -ForegroundColor Green
# Example 1: Simple JSON POST
# MODIFY: Change the data structure to match your API
# MODIFY: Replace URL with your endpoint
Write-Host "`n1. Simple JSON POST:" -ForegroundColor Yellow
$userData = @{
# MODIFY: Replace with the fields your API expects
name = "John Doe"
email = "john@example.com"
age = 30
# Add more fields as needed for your API
}
# DON'T CHANGE: This correctly converts PowerShell objects to JSON
$jsonBody = $userData | ConvertTo-Json
$headers = @{
# DON'T CHANGE: JSON APIs require this Content-Type
"Content-Type" = "application/json"
"Accept" = "application/json"
# MODIFY: Add authentication headers here
# "Authorization" = "Bearer $env:API_TOKEN"
}
try {
# MODIFY: Replace URL with your actual API endpoint
$response = Invoke-RestMethod -Uri "https://httpbin.org/post" -Method POST -Body $jsonBody -Headers $headers
Write-Host "✅ JSON POST successful!" -ForegroundColor Green
Write-Host "Data sent: $($response.json | ConvertTo-Json -Compress)" -ForegroundColor Cyan
} catch {
Write-Error "❌ JSON POST failed: $($_.Exception.Message)"
}
# Example 2: POST with authentication
# MODIFY: Set your API token and replace URL
Write-Host "`n2. Authenticated JSON POST:" -ForegroundColor Yellow
if ($env:API_TOKEN) {
$authData = @{
# MODIFY: Change data structure for your API
title = "Test Post"
content = "This is a test post via API"
category = "testing"
published = $true
}
$jsonBody = $authData | ConvertTo-Json
$authHeaders = @{
"Content-Type" = "application/json"
"Accept" = "application/json"
# DON'T CHANGE: This is the secure way to include auth
"Authorization" = "Bearer $env:API_TOKEN"
"User-Agent" = "PowerShell-API-Client" # MODIFY: Change to your app name
}
try {
# MODIFY: Replace with your authenticated endpoint
$response = Invoke-RestMethod -Uri "https://httpbin.org/post" -Method POST -Body $jsonBody -Headers $authHeaders
Write-Host "✅ Authenticated POST successful!" -ForegroundColor Green
} catch [System.Net.WebException] {
$statusCode = $_.Exception.Response.StatusCode
if ($statusCode -eq 401) {
Write-Error "❌ Authentication failed - check your API token"
} else {
Write-Error "❌ HTTP Error $statusCode: $($_.Exception.Message)"
}
}
} else {
Write-Warning "⚠️ Set `$env:API_TOKEN to test authenticated POST"
}
# Example 3: Form data POST (application/x-www-form-urlencoded)
# MODIFY: Change form fields to match your API
Write-Host "`n3. Form data POST:" -ForegroundColor Yellow
$formData = @{
# MODIFY: Replace with your form fields
username = "testuser"
password = "testpass123" # SECURITY: Use environment variables for real passwords
remember_me = "true"
}
# DON'T CHANGE: This is how PowerShell handles form data
$headers = @{
"Content-Type" = "application/x-www-form-urlencoded"
"Accept" = "application/json"
}
try {
# MODIFY: Replace URL with your form processing endpoint
$response = Invoke-RestMethod -Uri "https://httpbin.org/post" -Method POST -Body $formData -Headers $headers
Write-Host "✅ Form POST successful!" -ForegroundColor Green
Write-Host "Form data sent: $($response.form | ConvertTo-Json -Compress)" -ForegroundColor Cyan
} catch {
Write-Error "❌ Form POST failed: $($_.Exception.Message)"
}
# Example 4: POST with complex nested data
# MODIFY: Adjust structure to match your API's data model
Write-Host "`n4. Complex nested JSON POST:" -ForegroundColor Yellow
$complexData = @{
# MODIFY: Replace with your complex data structure
user = @{
personal_info = @{
first_name = "John"
last_name = "Doe"
email = "john.doe@example.com"
}
preferences = @{
theme = "dark"
notifications = $true
language = "en-US"
}
metadata = @{
source = "api"
timestamp = Get-Date -Format "yyyy-MM-ddTHH:mm:ssZ"
version = "1.0"
}
}
# Add arrays if your API supports them
tags = @("user", "new", "api-created")
}
$jsonBody = $complexData | ConvertTo-Json -Depth 10 # DON'T CHANGE: Depth needed for nested objects
$headers = @{
"Content-Type" = "application/json"
"Accept" = "application/json"
# MODIFY: Add authentication as needed
}
try {
# MODIFY: Replace with your endpoint that accepts complex data
$response = Invoke-RestMethod -Uri "https://httpbin.org/post" -Method POST -Body $jsonBody -Headers $headers
Write-Host "✅ Complex POST successful!" -ForegroundColor Green
Write-Host "Nested data preserved: $($response.json.user.personal_info.first_name)" -ForegroundColor Cyan
} catch {
Write-Error "❌ Complex POST failed: $($_.Exception.Message)"
}
# Example 5: File upload simulation (multipart/form-data)
# MODIFY: Replace with actual file path and upload endpoint
Write-Host "`n5. File upload simulation:" -ForegroundColor Yellow
Write-Host " (Note: This shows the concept - modify for real file uploads)" -ForegroundColor Gray
# For real file uploads, you'd typically use:
Write-Host " Real file upload pattern:" -ForegroundColor Cyan
Write-Host ' $filePath = "C:\path\to\your\file.txt"' -ForegroundColor Gray
Write-Host ' $fileContent = Get-Content $filePath -Raw' -ForegroundColor Gray
Write-Host ' # Use specialized upload methods or modules for multipart data' -ForegroundColor Gray
# Simulated file content for demo
$fileData = @{
# MODIFY: Replace with actual file metadata
filename = "test-file.txt"
content_type = "text/plain"
file_data = "This is simulated file content"
# Add other metadata your API requires
}
$jsonBody = $fileData | ConvertTo-Json
try {
# MODIFY: Replace with your file upload endpoint
$response = Invoke-RestMethod -Uri "https://httpbin.org/post" -Method POST -Body $jsonBody -Headers @{"Content-Type" = "application/json"}
Write-Host "✅ File upload simulation successful!" -ForegroundColor Green
} catch {
Write-Error "❌ File upload simulation failed: $($_.Exception.Message)"
}
# Example 6: POST with custom headers and error handling
# MODIFY: Add headers required by your specific API
Write-Host "`n6. POST with comprehensive error handling:" -ForegroundColor Yellow
$apiData = @{
# MODIFY: Structure this for your API
action = "create_record"
data = @{
title = "Test Record"
description = "Created via PowerShell API"
}
options = @{
validate = $true
notify = $false
}
}
$headers = @{
"Content-Type" = "application/json"
"Accept" = "application/json"
# MODIFY: Add your API's required headers
"X-API-Version" = "v1"
"X-Client-Type" = "PowerShell"
# "Authorization" = "Bearer $env:API_TOKEN" # Uncomment for auth
}
try {
$jsonBody = $apiData | ConvertTo-Json -Depth 5
# MODIFY: Replace with your actual endpoint
$response = Invoke-RestMethod -Uri "https://httpbin.org/post" -Method POST -Body $jsonBody -Headers $headers -TimeoutSec 30
Write-Host "✅ API POST successful!" -ForegroundColor Green
# MODIFY: Change how you handle the response
if ($response.json.action -eq "create_record") {
Write-Host "Record creation confirmed" -ForegroundColor Cyan
}
} catch [System.Net.WebException] {
# DON'T CHANGE: This properly handles HTTP errors
$statusCode = $_.Exception.Response.StatusCode
switch ($statusCode) {
400 { Write-Error "❌ Bad Request (400) - Check your data format" }
401 { Write-Error "❌ Unauthorized (401) - Check your authentication" }
403 { Write-Error "❌ Forbidden (403) - Check your permissions" }
422 { Write-Error "❌ Unprocessable Entity (422) - Check your data validation" }
500 { Write-Error "❌ Server Error (500) - API server issue" }
default { Write-Error "❌ HTTP Error $statusCode: $($_.Exception.Message)" }
}
} catch [System.TimeoutException] {
Write-Error "❌ Request timed out - API may be slow or unresponsive"
} catch {
Write-Error "❌ Unexpected error: $($_.Exception.Message)"
}
# Example 7: Real-world API POST (GitHub example)
# MODIFY: Set up GitHub token and adjust for your use case
Write-Host "`n7. Real-world example - GitHub Gist creation:" -ForegroundColor Yellow
if ($env:GITHUB_TOKEN) {
$gistData = @{
# MODIFY: Change gist content and settings
description = "PowerShell API Example Gist"
public = $false # Set to $true for public gists
files = @{
"example.ps1" = @{
content = "# This gist was created via PowerShell API`nWrite-Host 'Hello from API!'"
}
# Add more files if needed
}
}
$headers = @{
"Authorization" = "token $env:GITHUB_TOKEN"
"Accept" = "application/vnd.github.v3+json"
"Content-Type" = "application/json"
}
try {
$jsonBody = $gistData | ConvertTo-Json -Depth 5
$response = Invoke-RestMethod -Uri "https://api.github.com/gists" -Method POST -Body $jsonBody -Headers $headers
Write-Host "✅ GitHub Gist created successfully!" -ForegroundColor Green
Write-Host "Gist URL: $($response.html_url)" -ForegroundColor Cyan
Write-Host "Gist ID: $($response.id)" -ForegroundColor Cyan
} catch {
Write-Error "❌ GitHub Gist creation failed: $($_.Exception.Message)"
}
} else {
Write-Warning "⚠️ Set `$env:GITHUB_TOKEN to test GitHub POST operations"
}
Write-Host "`n=== POST Request Best Practices ===" -ForegroundColor Magenta
Write-Host "✏️ MODIFY FOR YOUR API:" -ForegroundColor Yellow
Write-Host " • Data structure - Match your API's expected format" -ForegroundColor White
Write-Host " • URLs - Replace with your actual endpoints" -ForegroundColor White
Write-Host " • Headers - Add required authentication and custom headers" -ForegroundColor White
Write-Host " • Content-Type - Use application/json for most APIs" -ForegroundColor White
Write-Host " • Error handling - Customize for your API's error codes" -ForegroundColor White
Write-Host "`n🔒 SECURITY NOTES:" -ForegroundColor Red
Write-Host " • Validate all input data before sending" -ForegroundColor White
Write-Host " • Use HTTPS for all POST requests" -ForegroundColor White
Write-Host " • Include authentication for protected endpoints" -ForegroundColor White
Write-Host " • Don't log sensitive POST data" -ForegroundColor White
Write-Host " • Set appropriate timeouts" -ForegroundColor White
Write-Host "`n⚠️ COMMON MISTAKES TO AVOID:" -ForegroundColor Yellow
Write-Host " • Forgetting ConvertTo-Json for complex objects" -ForegroundColor White
Write-Host " • Wrong Content-Type header" -ForegroundColor White
Write-Host " • Not handling authentication errors" -ForegroundColor White
Write-Host " • Sending unvalidated user input" -ForegroundColor White