Skip to main content
This guide shows how to test APIs that use API key authentication. Perfect for testing different API key placement methods and validation.

Use Cases

  • Test header-based API key authentication
  • Test query parameter API key authentication
  • Test invalid API key error handling
  • Validate missing API key responses

Simple Implementation

from locust import task, HttpUser
import random

class APIKeyTestUser(HttpUser):
    def on_start(self):
        # API keys for testing (replace with your actual keys)
        self.valid_key = "sk-1234567890abcdef"
        self.invalid_key = "invalid-key-12345"
        
        # API endpoints that require authentication
        self.endpoints = ["/api/users", "/api/data", "/api/reports"]

    @task(4)
    def test_header_api_key(self):
        """Test API key in header (X-API-Key: your-key)"""
        endpoint = random.choice(self.endpoints)
        
        headers = {
            "X-API-Key": self.valid_key,
            "Content-Type": "application/json"
        }
        
        with self.client.get(
            endpoint,
            headers=headers,
            name="Header API Key"
        ) as response:
            if response.status_code == 200:
                print(f"Header API key success: {endpoint}")
            elif response.status_code == 401:
                response.failure("Valid API key rejected")
            else:
                response.failure(f"Unexpected response: {response.status_code}")

    @task(3)
    def test_bearer_token_api_key(self):
        """Test API key as Bearer token (Authorization: Bearer your-key)"""
        endpoint = random.choice(self.endpoints)
        
        headers = {
            "Authorization": f"Bearer {self.valid_key}",
            "Content-Type": "application/json"
        }
        
        with self.client.get(
            endpoint,
            headers=headers,
            name="Bearer Token API Key"
        ) as response:
            if response.status_code == 200:
                print(f"Bearer token success: {endpoint}")
            elif response.status_code == 401:
                response.failure("Valid bearer token rejected")
            else:
                response.failure(f"Unexpected response: {response.status_code}")

    @task(3)
    def test_query_parameter_api_key(self):
        """Test API key in query parameter (?api_key=your-key)"""
        endpoint = random.choice(self.endpoints)
        
        params = {"api_key": self.valid_key}
        
        with self.client.get(
            endpoint,
            params=params,
            name="Query Parameter API Key"
        ) as response:
            if response.status_code == 200:
                print(f"Query parameter success: {endpoint}")
            elif response.status_code == 401:
                response.failure("Valid API key in query rejected")
            else:
                response.failure(f"Unexpected response: {response.status_code}")

    @task(2)
    def test_invalid_api_key(self):
        """Test with invalid API key"""
        endpoint = random.choice(self.endpoints)
        
        headers = {
            "X-API-Key": self.invalid_key,
            "Content-Type": "application/json"
        }
        
        with self.client.get(
            endpoint,
            headers=headers,
            name="Invalid API Key"
        ) as response:
            if response.status_code == 401:
                print(f"Invalid API key correctly rejected: {endpoint}")
            elif response.status_code == 200:
                response.failure("Invalid API key was accepted")
            else:
                print(f"Invalid API key returned {response.status_code}")

    @task(1)
    def test_missing_api_key(self):
        """Test request without API key"""
        endpoint = random.choice(self.endpoints)
        
        with self.client.get(
            endpoint,
            name="Missing API Key"
        ) as response:
            if response.status_code == 401:
                print(f"Missing API key correctly rejected: {endpoint}")
            elif response.status_code == 200:
                response.failure("Request without API key was accepted")
            else:
                print(f"Missing API key returned {response.status_code}")

Setup Instructions

  1. Replace self.valid_key with your actual API key
  2. Replace self.invalid_key with a test invalid key
  3. Update self.endpoints with your actual API endpoints
  4. Adjust authentication method if your API uses different headers

What This Tests

  • Header Authentication: Tests X-API-Key header method
  • Bearer Token: Tests Authorization: Bearer token method
  • Query Parameter: Tests api_key query parameter method
  • Error Handling: Validates rejection of invalid/missing keys

Best Practices

  • Use realistic API keys that match your API’s format
  • Test all authentication methods your API supports
  • Validate both success and failure scenarios
  • Monitor response times for different auth methods

Common Issues

  • API Key Format: Ensure test keys match your API’s expected format
  • Rate Limiting: Some APIs rate limit by API key, adjust test frequency
  • Permissions: Different API keys may have different permissions
  • Expiration: Check if your test API keys expire
I