DocumentationPowerShell API Testing Examples

PowerShell API Testing Examples

View on GitHub

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.

Overview

This collection provides PowerShell examples for common API testing scenarios, from basic GET requests to complex authentication patterns. Each script is designed to be educational, secure, and easily customizable for your specific API needs.

PowerShell Native

Uses built-in Invoke-RestMethod for maximum compatibility

Security Focused

Environment variables, proper error handling, input validation

Customizable

Clear guidance on what to modify and what to keep unchanged

Files Overview

FilePurposeWhat to ModifyKey Security Notes
basic-get-requests.ps1
Simple GET requests with headers and parametersURLs, headers, query params, timeoutsAlways use HTTPS, validate responses
authentication-examples.ps1
Various authentication methodsAPI endpoints, credential sourcesNever hardcode secrets, use env vars
post-requests.ps1
POST requests with JSON and form dataData structures, endpoints, content typesValidate input data, use HTTPS
error-handling.ps1
Comprehensive error handling patternsError messages, retry logic, timeout valuesDon't expose sensitive data in errors
utility-functions.ps1
Reusable functions for common operationsFunction parameters, validation rulesCustomize but keep core error handling

Quick Start

1

Set up credentials securely

Always use environment variables for API credentials

# 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"
2

Run any example script

Execute the scripts to see examples in action

.\basic-get-requests.ps1
.\authentication-examples.ps1
# etc.
3

Copy functions you need

Use the examples as building blocks for your projects

# Copy relevant functions into your own scripts
# Modify parameters and endpoints for your API

Basic GET Requests

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

Critical Security Rules

✅ ALWAYS do this:
$headers = @{"Authorization" = "Bearer $env:API_TOKEN"}
❌ NEVER do this:
$headers = @{"Authorization" = "Bearer abc123hardcoded"}

What it covers:

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

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

POST Requests

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

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

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

Utility Functions

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

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_token"
$env:API_KEY = "your_key"
$env:GITHUB_TOKEN = "ghp_token"
Command Prompt:
set API_TOKEN=your_token
set API_KEY=your_key
set GITHUB_TOKEN=ghp_token
Bash (Linux/Mac):
export API_TOKEN="your_token"
export API_KEY="your_key"
export GITHUB_TOKEN="ghp_token"

Resources & Support

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