Summary
API testing validates application programming interfaces directly at the business logic layer, ensuring data exchange, functionality, reliability, performance, and security without UI dependencies. Master REST/SOAP/GraphQL testing, HTTP methods, status codes, authentication mechanisms, and automation frameworks to excel in API testing interviews.
1. API Testing Fundamentals
What is API Testing?
- Testing application programming interfaces directly
- Validates functionality, reliability, performance, and security
- No GUI required - tests business logic layer
Key Differences: API vs UI Testing
| API Testing | UI Testing |
|---|---|
| Tests business logic | Tests presentation layer |
| Faster execution | Slower execution |
| More stable | Prone to UI changes |
| Early testing possible | Requires complete UI |
2. Types of APIs
REST API
- Stateless architecture
- Uses HTTP methods (GET, POST, PUT, DELETE, PATCH)
- JSON/XML data format
- Resource-based URLs
SOAP API
- Protocol-based
- XML only
- WSDL for service description
- Built-in security (WS-Security)
GraphQL
- Query language for APIs
- Single endpoint
- Client specifies exact data needed
- Reduces over/under-fetching
3. HTTP Methods & Status Codes
HTTP Methods
GET - Retrieve data
POST - Create new resource
PUT - Update entire resource
PATCH - Partial update
DELETE - Remove resource
HEAD - Get headers only
OPTIONS - Get allowed methods
Common Status Codes
2xx Success:
200 - OK
201 - Created
204 - No Content
3xx Redirection:
301 - Moved Permanently
304 - Not Modified
4xx Client Errors:
400 - Bad Request
401 - Unauthorized
403 - Forbidden
404 - Not Found
429 - Too Many Requests
5xx Server Errors:
500 - Internal Server Error
502 - Bad Gateway
503 - Service Unavailable
4. Types of API Testing
1. Functional Testing
- Validates expected functionality
- Tests with valid/invalid inputs
- Verifies response structure
2. Integration Testing
- Tests API integration with other components
- Database connections
- Third-party service integrations
3. Performance Testing
- Load Testing: Normal expected load
- Stress Testing: Beyond normal capacity
- Volume Testing: Large amounts of data
- Spike Testing: Sudden load increases
4. Security Testing
- Authentication & Authorization
- SQL Injection
- Cross-Site Scripting (XSS)
- Data encryption
- Rate limiting
5. Contract Testing
- Validates API meets agreed specifications
- Schema validation
- Response format verification
5. API Testing Tools
Popular Tools
- Postman - GUI-based, collaboration features
- REST Assured - Java library for REST APIs
- SoapUI - SOAP and REST testing
- JMeter - Performance testing
- Cypress - Modern web testing
- Newman - Postman CLI runner
- Insomnia - REST and GraphQL client
6. API Testing Best Practices
Test Design
Test Categories Priority:
- Positive tests (happy path)
- Negative tests (error scenarios)
- Edge cases
- Security tests
Data-Driven Testing:
- Parameterize test data
- Use external data sources
- Test multiple scenarios efficiently
Test Implementation
# Example: REST API test using Python requests
import requests
import pytest
def test_get_user():
response = requests.get('https://api.example.com/users/1')
assert response.status_code == 200
assert response.json()['id'] == 1
def test_create_user():
payload = {'name': 'John', 'email': 'john@test.com'}
response = requests.post('https://api.example.com/users', json=payload)
assert response.status_code == 201
assert response.json()['name'] == 'John'
Authentication Testing
// Example: Bearer token authentication
const axios = require('axios');
const config = {
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json'
}
};
axios.get('https://api.example.com/protected', config)
.then(response => console.log(response.data))
.catch(error => console.error(error));
7. Common API Testing Scenarios
1. CRUD Operations
Create: POST /api/users
Read: GET /api/users/{id}
Update: PUT /api/users/{id}
Delete: DELETE /api/users/{id}
2. Pagination Testing
- Test page size limits
- Verify total count
- Test first/last page
- Invalid page numbers
3. Filtering & Sorting
GET /api/products?category=electronics&sort=price&order=asc
4. Error Handling
- Missing required fields
- Invalid data types
- Malformed requests
- Unauthorized access
8. API Documentation Testing
What to Verify:
- Endpoint URLs accuracy
- Request/response examples
- Parameter descriptions
- Authentication requirements
- Rate limits
- Error responses
9. Advanced Concepts
API Versioning Strategies
- URI Versioning:
/api/v1/users - Header Versioning:
Accept: application/vnd.api+json;version=1 - Query Parameter:
/api/users?version=1
Rate Limiting Headers
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1619875200
Idempotency
- GET, PUT, DELETE should be idempotent
- POST is not idempotent
- Important for retry mechanisms
WebHooks Testing
- Verify payload structure
- Test retry mechanisms
- Validate signatures
- Check timeout handling
10. Critical Testing Scenarios
Testing Without Documentation
- OPTIONS Method: Discover allowed HTTP methods
- Network Traffic Analysis: Inspect browser/app requests
- Error Message Exploration: Reveal expected formats
- Common Endpoint Patterns: /api/v1/resources, /users, /auth
API Authentication Strategies
- Environment Variables: Store credentials securely
- Token Management: Implement refresh token logic
- Setup/Teardown: Initialize auth in test lifecycle
- Mock Authentication: For isolated testing
PUT vs PATCH Distinction
- PUT: Replaces entire resource, idempotent
- PATCH: Updates specific fields only, may not be idempotent
- Usage: PUT for full updates, PATCH for partial modifications
Payment API Testing Approach
- Sandbox Environment: Never use production
- Test Scenarios: Valid/invalid cards, expired, insufficient funds
- Idempotency Keys: Prevent duplicate charges
- Security Compliance: PCI DSS requirements
- Error Handling: Network failures, timeouts
Performance Testing Strategy
- Response Time Metrics: P50, P95, P99 percentiles
- Concurrent Users: Gradual load increase
- Resource Monitoring: CPU, memory, database connections
- Query Optimization: Identify N+1 queries, slow endpoints
11. API Test Automation Framework
Basic Structure:
api-test-framework/
├── tests/
│ ├── functional/
│ ├── integration/
│ └── performance/
├── utils/
│ ├── api_client.py
│ └── test_data.py
├── config/
│ └── environments.json
└── reports/
Sample Test Class:
class APITestBase:
def setup_method(self):
self.base_url = os.getenv('API_BASE_URL')
self.headers = {'Content-Type': 'application/json'}
def teardown_method(self):
# Cleanup test data
pass
def send_request(self, method, endpoint, **kwargs):
url = f"{self.base_url}{endpoint}"
return requests.request(method, url, headers=self.headers, **kwargs)
12. Debugging Tips
Common Issues:
- CORS errors: Check allowed origins
- SSL certificate: Verify certificate validity
- Timeout errors: Increase timeout limits
- Encoding issues: Check Content-Type headers
Tools for Debugging:
- Browser DevTools (Network tab)
- Charles Proxy / Fiddler
- Wireshark for low-level analysis
- API logs and monitoring tools
13. CI/CD Integration
Pipeline Steps:
# Example: GitHub Actions
- name: Run API Tests
run: |
npm install
npm run test:api
newman run collection.json -e prod.json
Best Practices:
- Run tests in isolated environments
- Use test data cleanup
- Parallel test execution
- Generate test reports
14. Key Metrics to Track
- Response Time: Average, median, 95th percentile
- Error Rate: Failed requests percentage
- Throughput: Requests per second
- Test Coverage: Endpoints tested
- Availability: Uptime percentage
15. Interview Preparation Checklist
Core Concepts to Master
- REST Principles: Stateless, cacheable, uniform interface, client-server, layered system
- HTTP Methods: GET (safe), POST (not idempotent), PUT/DELETE (idempotent)
- Status Codes: 2xx (success), 3xx (redirect), 4xx (client error), 5xx (server error)
- Authentication: Basic, Bearer tokens, OAuth 2.0, API keys, JWT
- Data Validation: JSON Schema, XML Schema, contract testing
- Versioning: URI (/v1/), header, query parameter strategies
- Rate Limiting: Token bucket, sliding window algorithms
- CORS: Preflight requests, allowed origins, credentials
Technical Skills to Demonstrate
- CRUD Testing: Complete lifecycle validation
- Authentication Handling: Token management, refresh logic
- Data-Driven Testing: CSV, JSON, database sources
- Mocking: WireMock, stubbing external services
- Performance Testing: JMeter, k6, Gatling
- Security Testing: OWASP API Top 10
- CI/CD Integration: Newman, Jenkins, GitHub Actions
- Reporting: Allure, ExtentReports, custom dashboards
Key Testing Principles
- Test both happy path and edge cases
- Validate response structure, not just status
- Check headers, cookies, and metadata
- Measure performance characteristics
- Ensure backward compatibility
- Implement proper test data cleanup
Found this useful? Pass it on.