API Automation
Advanced REST and GraphQL API testing, load testing, and performance automation scripts
REST API Testing with Python
import requests
import json
class APITestClient:
def __init__(self, base_url, auth_token=None):
self.base_url = base_url
self.session = requests.Session()
if auth_token:
self.session.headers['Authorization'] = f'Bearer {auth_token}'
def get(self, endpoint, params=None):
response = self.session.get(f"{self.base_url}{endpoint}", params=params)
return self._handle_response(response)
def post(self, endpoint, data=None):
response = self.session.post(f"{self.base_url}{endpoint}", json=data)
return self._handle_response(response)
def _handle_response(self, response):
response.raise_for_status()
return response.json()
# Usage
client = APITestClient("https://api.example.com", "your-token")
users = client.get("/users", {"page": 1, "limit": 10})
new_user = client.post("/users", {"name": "John", "email": "john@example.com"})GraphQL Testing
import requests
class GraphQLClient:
def __init__(self, endpoint, headers=None):
self.endpoint = endpoint
self.headers = headers or {'Content-Type': 'application/json'}
def query(self, query, variables=None):
payload = {'query': query}
if variables:
payload['variables'] = variables
response = requests.post(self.endpoint, json=payload, headers=self.headers)
return response.json()
# Usage
client = GraphQLClient("https://api.example.com/graphql")
result = client.query("""
query GetUsers($limit: Int!) {
users(limit: $limit) {
id
name
email
}
}
""", {"limit": 10})Load Testing with Locust
from locust import HttpUser, task, between
class APILoadTest(HttpUser):
wait_time = between(1, 3)
def on_start(self):
# Login and get token
response = self.client.post("/auth/login", json={
"email": "test@example.com",
"password": "password123"
})
self.token = response.json()["token"]
self.client.headers = {"Authorization": f"Bearer {self.token}"}
@task(3)
def get_users(self):
self.client.get("/users")
@task(1)
def create_user(self):
self.client.post("/users", json={
"name": "Load Test User",
"email": f"user_{time.time()}@test.com"
})
# Run: locust -f locustfile.py --host=https://api.example.comAPI Testing Best Practices
- • Test all HTTP methods (GET, POST, PUT, DELETE)
- • Validate response status codes and body structure
- • Test authentication and authorization flows
- • Include negative test cases and error handling
- • Test rate limiting and pagination
Performance Testing Metrics
- • Response time (p50, p95, p99 percentiles)
- • Throughput (requests per second)
- • Error rate under load
- • Concurrent user capacity
- • Resource utilization (CPU, memory)