Skip to content

jumpboxtech/powershell-test-api-calls

Repository files navigation

PowerShell API Testing Examples

A comprehensive collection of PowerShell scripts for testing REST APIs securely and effectively. Each script focuses on a specific aspect of API interaction with detailed explanations, security considerations, and customization guidance.

πŸ“ Files Overview

File Purpose What to Modify Key Security Notes
basic-get-requests.ps1 Simple GET requests with headers and parameters URLs, headers, query params, timeouts Always use HTTPS, validate responses
authentication-examples.ps1 Various authentication methods API endpoints, credential sources Never hardcode secrets, use env vars
post-requests.ps1 POST requests with JSON and form data Data structures, endpoints, content types Validate input data, use HTTPS
error-handling.ps1 Comprehensive error handling patterns Error messages, retry logic, timeout values Don't expose sensitive data in errors
utility-functions.ps1 Reusable functions for common operations Function parameters, validation rules Customize but keep core error handling

πŸš€ Quick Start

  1. Set up credentials securely:
# Set environment variables (NEVER hardcode in scripts)
$env:API_TOKEN = "your_bearer_token_here"
$env:API_KEY = "your_api_key_here"
$env:GITHUB_TOKEN = "ghp_your_github_token_here"
  1. Run any example script:
.\basic-get-requests.ps1
.\authentication-examples.ps1
# etc.
  1. Copy functions you need into your own scripts

πŸ“– Detailed Guide

Basic GET Requests

File: basic-get-requests.ps1

What it covers:

  • Simple GET requests to public APIs
  • Adding custom headers for identification
  • URL parameters and query strings
  • Timeout handling and control
  • Real-world API examples

What you SHOULD modify:

# βœ… Change these for your API:
$response = Invoke-RestMethod -Uri "https://YOUR-API.com/endpoint" -Method GET

$customHeaders = @{
    "User-Agent" = "YourApp/1.0"        # Your app name
    "Accept" = "application/json"        # Keep for JSON APIs
    "Authorization" = "Bearer $env:TOKEN" # Your auth method
}

$queryParams = @{
    # Replace with your API's parameters
    search = "your-query"
    limit = 10
    format = "json"
}

What you SHOULDN'T change:

  • The basic Invoke-RestMethod structure
  • Error handling patterns (try/catch blocks)
  • Query string building logic
  • Timeout implementation

Security considerations:

  • Always use HTTPS endpoints in production
  • Never include sensitive data in URL parameters
  • Set appropriate timeouts to prevent hanging requests
  • Validate all response data before using it

Authentication Examples

File: authentication-examples.ps1

What it covers:

  • Bearer token authentication (most secure)
  • API key in headers
  • Basic username/password authentication
  • Custom authentication headers
  • Real GitHub API examples

Critical security rules:

# βœ… ALWAYS do this:
$headers = @{"Authorization" = "Bearer $env:API_TOKEN"}

# ❌ NEVER do this:
$headers = @{"Authorization" = "Bearer abc123hardcoded"}

What you SHOULD modify:

# Authentication header names (change for your API):
"X-API-Key" = $env:API_KEY           # Some APIs use this
"Authorization" = "Bearer $env:TOKEN" # Most common
"X-Auth-Token" = $env:TOKEN          # Alternative format

# API endpoints:
$response = Invoke-RestMethod -Uri "https://YOUR-API.com/protected" -Headers $headers

What you SHOULDN'T change:

  • Environment variable approach for storing secrets
  • Base64 encoding method for Basic auth
  • Error handling for 401/403 responses
  • The overall authentication patterns

Security requirements:

  • Always use environment variables for API keys and tokens
  • Use Get-Credential for interactive scripts requiring passwords
  • Prefer Bearer tokens over API keys when possible
  • Always use HTTPS with authentication
  • Implement proper error handling to avoid exposing credentials

POST Requests

File: post-requests.ps1

What it covers:

  • JSON POST requests with authentication
  • Form data submissions
  • Complex nested data structures
  • File upload patterns
  • Comprehensive error handling for POST operations

What you SHOULD modify:

# Data structure (match your API's expected format):
$userData = @{
    name = "John Doe"           # Change field names
    email = "john@example.com"  # Change data types
    preferences = @{            # Add nested objects
        theme = "dark"
        notifications = $true
    }
}

# Content-Type for your API:
"Content-Type" = "application/json"              # Most APIs
"Content-Type" = "application/x-www-form-urlencoded"  # Form data
"Content-Type" = "application/xml"              # XML APIs

What you SHOULDN'T change:

  • ConvertTo-Json usage for object-to-JSON conversion
  • Content-Type header setting patterns
  • Error handling for HTTP status codes
  • The basic POST request structure

Security considerations:

  • Validate all input data before sending
  • Use HTTPS for all POST requests containing sensitive data
  • Include proper authentication headers
  • Be careful with file uploads and size limits
  • Never log sensitive POST data in plain text

Error Handling

File: error-handling.ps1

What it covers:

  • HTTP status code handling (400, 401, 403, 404, 500, etc.)
  • Timeout management and recovery
  • Retry logic with exponential backoff
  • Authentication error patterns
  • Comprehensive logging strategies

What you SHOULD modify:

# Timeout values (based on your API's performance):
$response = Invoke-RestMethod -Uri $uri -TimeoutSec 30  # Adjust as needed

# Retry strategies:
$MaxRetries = 5           # Increase for unreliable APIs
$BaseDelaySeconds = 2     # Adjust base delay

# Custom error messages:
switch ($statusCode) {
    400 { Write-Error "Check your request format for this API" }
    401 { Write-Error "Your API token has expired" }
    # Customize messages for your users
}

What you SHOULDN'T change:

  • Try/catch block structure and patterns
  • [System.Net.WebException] type checking
  • HTTP status code extraction method: [int]$_.Exception.Response.StatusCode
  • Exponential backoff algorithm
  • Exception propagation with throw

Security considerations:

  • Don't log sensitive data in error messages
  • Sanitize error responses before displaying to end users
  • Implement rate limiting to prevent abuse during retries
  • Be careful not to expose internal API details in error messages

Utility Functions

File: utility-functions.ps1

What it covers:

  • Generic API caller with retry logic
  • Authenticated API helper functions
  • Response validation utilities
  • Batch API operations with rate limiting
  • API health checking tools
  • Configuration management helpers

How to use these functions:

  1. Copy the functions you need into your scripts
  2. Modify parameters and defaults for your specific APIs
  3. Add your API-specific logic where indicated in comments
  4. Use as building blocks for more complex operations

What you SHOULD modify:

# Function defaults:
[int]$TimeoutSec = 30        # Adjust for your API
[int]$MaxRetries = 3         # Adjust retry attempts
[string]$Version = "v1"      # Your API version

# Authentication methods:
$headers["Authorization"] = "Bearer $Token"      # Most common
$headers["X-API-Key"] = $Token                  # Alternative
$headers[$ApiKeyHeader] = $Token                # Custom header

# Validation rules:
[string[]]$RequiredFields = @("id", "name", "status")  # Your required fields

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

πŸ”’ Security Best Practices

βœ… DO:

  • Use environment variables for all API keys and tokens
  • Use HTTPS endpoints exclusively in production
  • Set appropriate timeouts to prevent hanging requests
  • Validate all response data before using it
  • Implement proper error handling for all requests
  • Use Get-Credential for interactive credential input
  • Rotate API keys regularly
  • Monitor API usage and rate limits

❌ DON'T:

  • Never hardcode API keys or passwords in scripts
  • Don't put credentials in query parameters
  • Don't ignore authentication errors
  • Don't log sensitive data in plain text
  • Don't use HTTP for authenticated requests
  • Don't commit secrets to source control
  • Don't expose internal API details in user-facing errors

πŸ”§ Environment Variable Setup

PowerShell (Windows):

$env:API_TOKEN = "your_bearer_token"
$env:API_KEY = "your_api_key"
$env:GITHUB_TOKEN = "ghp_your_github_token"

Command Prompt (Windows):

set API_TOKEN=your_bearer_token
set API_KEY=your_api_key
set GITHUB_TOKEN=ghp_your_github_token

Bash (Linux/Mac):

export API_TOKEN="your_bearer_token"
export API_KEY="your_api_key"
export GITHUB_TOKEN="ghp_your_github_token"

πŸ› οΈ Customization Guide

For Each Script:

  1. Replace URLs with your actual API endpoints
  2. Modify data structures to match your API's requirements
  3. Adjust authentication headers and methods
  4. Customize error handling for your specific use cases
  5. Set appropriate timeouts based on your API's performance

Common Modifications:

# Change base URLs:
"https://httpbin.org/get" β†’ "https://your-api.com/endpoint"

# Update authentication:
"Authorization" = "Bearer $env:API_TOKEN" β†’ "X-API-Key" = "$env:API_KEY"

# Adjust data structures:
@{ name = "test"; email = "test@example.com" } β†’ @{ title = "Post"; content = "Content" }

# Modify timeouts:
-TimeoutSec 30 β†’ -TimeoutSec 60  # For slower APIs

πŸ“‹ Real-World Examples

GitHub API Integration:

# Set your token first
$env:GITHUB_TOKEN = "ghp_your_token_here"

# Get user info
$headers = @{"Authorization" = "token $env:GITHUB_TOKEN"}
$user = Invoke-RestMethod -Uri "https://api.github.com/user" -Headers $headers

# Create a gist
$gist = @{
    description = "My API test"
    files = @{ "test.txt" = @{ content = "Hello API!" } }
} | ConvertTo-Json -Depth 3

Invoke-RestMethod -Uri "https://api.github.com/gists" -Method POST -Body $gist -Headers $headers

Generic REST API:

# Set your credentials
$env:API_TOKEN = "your_token_here"

# Configuration
$baseUrl = "https://api.yourservice.com"
$headers = @{
    "Authorization" = "Bearer $env:API_TOKEN"
    "Content-Type" = "application/json"
}

# GET data
$users = Invoke-RestMethod -Uri "$baseUrl/users" -Headers $headers

# POST new data
$newUser = @{ name = "John"; email = "john@example.com" } | ConvertTo-Json
$created = Invoke-RestMethod -Uri "$baseUrl/users" -Method POST -Body $newUser -Headers $headers

πŸ› Troubleshooting

Common Issues:

SSL/TLS Certificate Errors:

# For testing only (not recommended for production):
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

Authentication Failures:

  • Verify your API key/token is valid and not expired
  • Check the authentication method (Bearer vs API key vs Basic)
  • Ensure you have the required permissions
  • Verify the header format matches your API's requirements

Timeout Issues:

# Increase timeout for slower APIs:
Invoke-RestMethod -Uri $uri -TimeoutSec 60

Rate Limiting:

# Add delays between requests:
Start-Sleep -Milliseconds 1000  # 1 second delay

πŸ“„ License

MIT License - Feel free to use and modify these examples for your projects.

🀝 Contributing

These examples are meant to be educational and customizable. Feel free to:

  • Adapt them for your specific APIs
  • Add additional error handling
  • Implement new authentication methods
  • Share improvements with the community

Remember: Security is paramount when working with APIs. Always protect your credentials and validate your data! πŸ”’

About

PowerShell API testing examples with security best practices. GET/POST requests, authentication, error handling, and utility functions.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors