0% found this document useful (0 votes)
104 views90 pages

Comprehensive API Testing Guide

The document is a comprehensive guide on API testing, covering its importance, methods, and tools like Postman. It details various testing types, including functional, performance, and security testing, along with best practices and common mistakes to avoid. Additionally, it outlines a learning path for beginners to advanced users and provides practical examples and testing strategies for real-world applications.

Uploaded by

rasikakolhe04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
104 views90 pages

Comprehensive API Testing Guide

The document is a comprehensive guide on API testing, covering its importance, methods, and tools like Postman. It details various testing types, including functional, performance, and security testing, along with best practices and common mistakes to avoid. Additionally, it outlines a learning path for beginners to advanced users and provides practical examples and testing strategies for real-world applications.

Uploaded by

rasikakolhe04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

API Testing

Complete Documentation

Complete Zero to Hero Guide • 60+ Slides


What is API Testing?
API testing verifies that applications communicate reliably, securely, and efficiently.

• Tests functionality, performance, and security


• Ensures data flows correctly between systems
• Critical for production reliability
• More cost-effective than manual UI testing
Why API Testing Matters

✓ Catches Bugs
100x cheaper early

Performance
Ensures fast responses

Security
Prevents vulnerabilities
HTTP Methods (REST API)
• GET: Retrieve data from server
• POST: Create new resource
• PUT: Replace entire resource
• PATCH: Partial update to resource
• DELETE: Remove resource
HTTP Status Codes

2xx Success
200 OK, 201 Created

4xx Client Error


400, 401, 404

5xx Server Error


500, 502, 503
Postman: #1 API Testing Tool
Used by millions of developers worldwide.

• Easy-to-use interface for manual testing


• Create automated test suites with collections
• Write test scripts with JavaScript
• Generate API documentation automatically
Creating API Test Cases
A good test case includes:

• Test ID: Unique identifier (TC_API_001)


• Endpoint: API URL being tested
• Input Data: Request parameters
• Expected Result: What should happen
Positive vs Negative Testing

✓ Positive (Happy Path)


Test scenarios where API should succeed with valid data

✗ Negative (Error Handling)


Test with invalid data and error scenarios
Types of API Parameters
• Path: /users/123 (identify resource)
• Query: ?page=1&limit=10 (filter/paginate)
• Header: Authorization: Bearer token
• Body: JSON object in POST/PUT/PATCH
Authentication & Authorization
Critical security testing:

• API Key authentication (simple key-based)


• OAuth 2.0 (industry standard)
• JWT Tokens (stateless auth)
• Test expired/invalid tokens return 401
Security Vulnerabilities to Test
• SQL Injection: Malicious SQL in inputs
• XSS Attacks: Malicious scripts
• Auth Bypass: Access without credentials
• Data Exposure: Sensitive data leaked
Functional Testing Checklist
• ✓ Status code matches expectation
• ✓ Response body is valid JSON
• ✓ All required fields present
• ✓ Data types are correct
• ✓ Error messages are helpful
Performance Testing Metrics
• Response Time: Target < 500ms
• Throughput: Requests per second
• Error Rate: Target < 1%
• CPU/Memory: Resource utilization
Load Testing Tools

JMeter
Enterprise testing

k6
DevOps & CI/CD

Locust
Python-based
Integration Testing
Verify APIs work correctly together:

• API with database (data flows correctly)


• Multiple APIs calling each other
• API with third-party services
• Data consistency across systems
GraphQL APIs (Modern Alternative)
Key differences from REST:

• Single endpoint instead of multiple


• Client requests specific fields only
• Flexible query language
• Errors returned with 200 status code
API Versioning Strategies
• URL: /api/v1/users vs /api/v2/users
• Header: Accept: application/[Link].v2+json
• Query: ?version=1
• Ensure backward compatibility with old clients
Contract Testing
Ensures backward compatibility:

• Prevent breaking changes between versions


• Allow independent deployment
• Catch incompatibilities early
• Consumer defines expectations
Automating Tests with Postman
• Write JavaScript test scripts for assertions
• Use environment variables for dynamic values
• Run collections with Newman CLI
• Integrate into CI/CD pipelines
CI/CD Pipeline for APIs
• Developer commits code to repository
• Pipeline automatically runs unit & API tests
• Security tests verify no vulnerabilities
• Performance tests check speed
• Auto-deploy if all tests pass
The Testing Pyramid
Distribute tests efficiently:

70% Unit Tests (Fast)


20% Integration Tests
10% E2E Tests (Slow)
Popular API Testing Tools
• Postman: Most beginner-friendly
• SoapUI: Complex SOAP & REST testing
• Insomnia: Lightweight alternative
• Thunder Client: VS Code extension
Real-World: E-Commerce API
Test key flows:

• Get product list with filters & pagination


• Add items to shopping cart
• Apply discount codes correctly
• Create order and process payment securely
Real-World: Social Media API
Critical test scenarios:

• User authentication and session management


• Create and delete posts with media
• Like, comment, share functionality
• Follow/unfollow users securely
10 Best Practices
• Test positive AND negative scenarios
• Verify error handling thoroughly
• Never test in production environment
• Use proper test data management
• Automate repetitive test cases
Common Mistakes to Avoid
• Only testing the happy path scenarios
• Hard-coding values instead of using variables
• Ignoring security and authentication testing
• Not checking response body content
Key Test Metrics
• Test Coverage: % of endpoints tested
• Pass Rate: % of tests passing
• Defect Density: Bugs per 100 tests
• MTTR: Mean time to fix bugs
Learning Path: Beginner (Month 1-2)
• Understand HTTP methods and REST basics
• Learn Postman for manual API testing
• Create simple test cases for CRUD operations
• Understand status codes and error handling
Learning Path: Intermediate (Month 3-6)
• Master Postman collections and test scripts
• Learn API security testing fundamentals
• Understand performance testing basics
• Automate tests with Newman CLI
Learning Path: Advanced (Month 7+)
• GraphQL API testing
• Advanced security testing (OWASP)
• Load and stress testing at scale
• Design comprehensive testing strategies
Tools to Master
Essential:

• Postman (API testing & automation)


• Git (version control)
• JIRA (bug tracking)

Advanced:

• JMeter, k6 (performance testing)


Programming Skills to Develop
• JavaScript: Write Postman test scripts
• Python: Automation and custom scripts
• SQL: Query databases for verification
• REST/HTTP: Understanding API concepts
API Mocking (When Real API Not Ready)
• Test frontend before backend API ready
• Simulate error scenarios easily
• Speed up test execution
• Reduce dependencies on real services
OpenAPI & Swagger Documentation
Benefits:

• Machine-readable API specifications


• Auto-generation of test cases
• Validation against specification
• Interactive API exploration with Swagger UI
Before You Test: Checklist
• ✓ API documentation reviewed
• ✓ Test environment access verified
• ✓ Test data prepared or seeded
• ✓ Necessary credentials obtained
• ✓ Test cases designed
Your Action Plan: Next 30 Days
• Week 1: Learn HTTP basics and Postman
• Week 2: Create 10 test cases
• Week 3: Master Postman collections
• Week 4: Explore automation & CI/CD
Key Takeaways
• API testing covers multiple dimensions
• Automate tests for efficiency
• Test positive AND negative scenarios
• Security testing is non-negotiable
• Use staging environment, never production
Continue Your Journey
• Practice with public APIs (JSONPlaceholder, PokéAPI)
• Build a portfolio of test cases
• Master automation with Postman/Newman
• Learn performance testing tools
• Stay updated with latest technologies
What Happens During API Call?
Step-by-step flow:

• Client sends HTTP request to server


• Server processes request and accesses database
• Server returns response with data and status code
• Client receives and processes response
• Application displays data to user
Request vs Response: Detailed

REQUEST
Headers: Auth token
Body: Data to send
Method: GET/POST

RESPONSE
Status: 200, 404, 500
Headers: Content-Type
Body: JSON data
Understanding JSON Format
Example API Response:

• {
• "id": 1,
• "name": "John",
• "email": "john@[Link]",
• "active": true
• }
Postman Interface: Key Areas
• URL Bar: Where you paste API endpoint
• Method Dropdown: Select GET/POST/PUT/PATCH/DELETE
• Headers Tab: Add Authorization, Content-Type
• Body Tab: Raw JSON for POST/PUT requests
• Send Button: Execute the API call
Postman Example: GET Request
Scenario: Fetch user by ID

• Method: GET
• URL: [Link]
• Headers: Authorization: Bearer token123
• Body: None (GET doesn't have body)
• Expected: 200 OK with user data
Postman Example: POST Request
Scenario: Create new user

• Method: POST
• URL: [Link]
• Body (JSON):
• {
• "name": "Alice",
• "email": "alice@[Link]"
• }
• Expected: 201 Created
Postman Example: PUT Request
Scenario: Replace entire user

• Method: PUT
• URL: [Link]
• Body (JSON):
• {
• "name": "Alice Updated",
• "email": "[Link]@[Link]"
• }
• Expected: 200 OK
Postman Example: DELETE Request
Scenario: Delete user

• Method: DELETE
• URL: [Link]
• Headers: Authorization: Bearer token123
• Body: None
• Expected: 204 No Content
HTTP Status Codes Explained
• 200 OK: Success, request worked perfectly
• 201 Created: New resource successfully created
• 204 No Content: Success but no data to return
• 400 Bad Request: Your data format is wrong
• 401 Unauthorized: You're not authenticated
More HTTP Status Codes
• 403 Forbidden: Authenticated but no permission
• 404 Not Found: Resource doesn't exist
• 500 Internal Server Error: Server crashed/error
• 502 Bad Gateway: Server temporarily unavailable
• 503 Service Unavailable: Server maintenance
Important Request Headers
• Content-Type: application/json
• Authorization: Bearer eyJhbGciOi...
• Accept: application/json
• User-Agent: PostmanRuntime/7.29.2
• X-API-Key: your-api-key-123

Headers tell the server what kind of data you're sending


Data Validation Testing
What to test:

• Required fields are enforced


• Email format is validated
• Phone numbers have correct length
• Dates are in correct format (YYYY-MM-DD)
• Numbers are within valid range
Validation Test Example
Test Case: Register user with invalid email

• POST /auth/register
• Body:
• {
• "email": "not-an-email",
• "password": "Pass123!"
• }
• Expected: 400 Bad Request
• Error Message: "Invalid email format"
Boundary Testing
Testing edge cases and limits:

• Empty strings: "" (should fail)


• Maximum length: 255 chars (test both 254, 255, 256)
• Minimum value: -1 (test edge of range)
• Negative numbers: -100 (when not allowed)
• Null values: null (should fail)
Rate Limiting Testing
Test API limits:

• Send 100 requests in 1 second


• Expected: 429 Too Many Requests after limit
• Check response headers for rate limit info
• X-RateLimit-Remaining: 45
• X-RateLimit-Reset: 1234567890
Timeout Testing
Test slow responses:

• Set Postman timeout to 5 seconds


• Call endpoint that takes 10 seconds
• Expected: Timeout error after 5 seconds
• API should handle slow connections gracefully
• Never leave timeout as infinite
Error Message Testing
Good error message example:

• {
• "error": true,
• "message": "Email already exists",
• "field": "email"
• }

Bad error message example:


• { "error": "DB Error 42" }
Query Parameter Testing
Example: List users with filters

• GET /users?page=1&limit=10&role=admin
• Test cases:
• Missing limit: /users?page=1
• Invalid page: /users?page=-1
• Limit too large: /users?limit=10000
Response Time Testing
Typical response times:

• Simple GET: 100-200ms (acceptable)


• Database query: 200-500ms (acceptable)
• Complex calculation: 500-2000ms (monitor)
• File upload: Can be slower (depends on size)
• Anything > 5000ms: Usually a problem
Content Type Testing
Different request formats:

• application/json - Standard (JSON body)


• application/x-www-form-urlencoded - Form data
• multipart/form-data - File uploads
• application/xml - XML format
• API should accept only correct types
File Upload Testing
Test cases:

• Valid file upload: .jpg, .pdf (should pass)


• Large file: 100MB (should fail with 413)
• Wrong type: .exe file (should reject)
• Empty file: 0 bytes (should handle)
• Corrupted file: Data corruption (should fail)
Pagination Testing
Example API response with pagination:

• {
• "data": [{...}, {...}],
• "pagination": {
• "page": 1,
• "limit": 10,
• "total": 100,
• "pages": 10
• }
• }
Filter Testing
Test filtering examples:

• GET /products?category=electronics
• GET /products?price_min=100&price_max=500
• GET /products?brand=Apple&in_stock=true
• GET /products?search=laptop (text search)
• GET /products?sort=price_asc (sorting)
CORS Testing
Check for CORS headers:

• Access-Control-Allow-Origin: * or specific domain


• Access-Control-Allow-Methods: GET, POST, PUT
• Access-Control-Allow-Headers: Content-Type, Authorization
• Access-Control-Max-Age: 3600 (cache time)
• Missing CORS: Browser blocks request
Bearer Token Testing
Test scenarios:

• Missing token: Should return 401


• Invalid token: "abc123xyz" should return 401
• Expired token: Should return 401
• Wrong format: "Bearer" should return 401
• Valid token: Request should succeed with 200
Response Consistency Testing
Verify consistency:

• Same request always returns same fields


• Data types are consistent (number not string)
• Date formats are consistent (YYYY-MM-DD)
• Error format always matches
• Empty values handled consistently (null vs "")
Database Integrity Testing
Verify data integrity:

• Create record via API, check in database


• Update via API, verify changes persisted
• Delete via API, confirm removal from DB
• Check foreign key relationships intact
• Verify timestamps are correct
Concurrent Request Testing
Simulate multiple users:

• Send 10 requests simultaneously


• API should handle without data corruption
• Order shouldn't matter for independent requests
• No race conditions in database
• Response times should remain consistent
Documentation Testing
Verify documentation matches implementation:

• Endpoint URL is correct


• HTTP method matches docs
• Required parameters listed accurately
• Response format matches examples
• Error codes are documented correctly
Role-Based Access Testing
Test different user roles:

• Admin: Can do everything


• User: Can access own data only
• Guest: Read-only access
• User accessing other's data: 403 Forbidden
• Deleted user: 401 Unauthorized
SQL Injection Testing
Test malicious input:

• Test case:
• POST /login
• email: admin' OR '1'='1
• password: anything
• Expected: 400 or 401 error
XSS Testing
Test script injection:

• Test case:
• POST /comments
• content: <script>alert('hacked')</script>
• Expected: Script removed/escaped
• API should sanitize user input
Default Credentials Testing
Test for security gaps:

• Try admin/admin login


• Try default ports (8080, 3306)
• Check for hidden admin panels
• Look for debug mode enabled
• Check for hardcoded credentials in code
HTTPS vs HTTP Testing
Security requirements:

• HTTP (non-encrypted): Never for sensitive data


• HTTPS (encrypted): Required for production
• Certificate validation: Must verify
• HTTP to HTTPS redirect: Should auto-redirect
• API keys over HTTPS only: Critical security
Creating Postman Collections
Organize tests:

• Create folder for each API section


• Folder: User Management (5 requests)
• Folder: Product Management (4 requests)
• Folder: Orders (3 requests)
• Run entire collection with one click
Postman Variables & Environments
Why use variables:

• {{baseUrl}}: Switch between dev/staging/prod


• {{token}}: Reuse auth token across requests
• {{userId}}: Use response data in next request
• {{timestamp}}: Generate dynamic values
• Makes collection portable and reusable
Writing Test Scripts in Postman
Example test script:

• [Link]("Status 200", () => {


• [Link](200);
• });
• [Link]("Response time < 500ms", () => {
• [Link]([Link]).to
• .[Link](500);
• });
Newman CLI for CI/CD
Running collections from command line:

• npm install -g newman


• newman run [Link] \
• e [Link] \
• r html
• Generates HTML report automatically
Real Example: User Registration Flow
Test sequence:

• 1. Register new user (email, password)


• 2. Verify 201 Created returned
• 3. Check user_id in response
• 4. Try login with new credentials
• 5. Get auth token, verify valid
Real Example: E-Commerce Checkout
Complete flow:

• 1. GET /products (list items)


• 2. POST /cart (add item)
• 3. POST /cart/coupon (apply discount)
• 4. POST /order (create order)
• 5. POST /payment (process payment)
• 6. Verify order status = "confirmed"
Common API Errors & Fixes
• CORS error: Add CORS headers on server
• Invalid JSON: Use JSON formatter tool
• 401 error: Check token validity
• 404 error: Verify endpoint URL
• 500 error: Check server logs
API Debugging Techniques
Debug checklist:

• Check URL spelling and parameters


• Verify headers are set correctly
• Validate JSON body format
• Look at raw request/response
• Check server logs for errors
• Use network browser tools (DevTools)
Test Environment Setup
Environment layers:

• Local: Developer machine (fast, isolated)


• Dev: Shared development server
• Staging: Prod-like environment (test here!)
• Production: Live (never test here)
Test Data Management
Best practices:

• Use realistic test data (fake but valid)


• Create, clean, recreate data for each test
• Never use production data
• Keep test data in version control
• Seed data with scripts for consistency
Testing Multiple API Versions
Version testing:

• v1: Old, stable, fewer features


• v2: Current, more features
• v3: New, beta features
• Test both versions for compatibility
• Ensure v1 requests still work
Testing Webhooks
Webhook testing approach:

• Use ngrok to expose local endpoint


• Register webhook with API
• Trigger event (e.g., payment processed)
• Verify webhook is called with correct data
• Test retry logic on failure
Async Operation Testing
Testing async APIs:

• GET /jobs/123/status (check job status)


• Returns: "pending", "processing", "completed"
• Test polling mechanism
• Verify final result is correct
• Check timeout scenarios
Monitoring APIs in Production
What to monitor:

• Uptime: API availability percentage


• Response time: Average latency
• Error rate: 4xx and 5xx percentage
• Throughput: Requests per second
• Set up alerts for anomalies
API Testing Best Practices Summary
• Always test in staging, never production
• Cover positive, negative, and edge cases
• Automate repetitive tests
• Test security thoroughly
• Monitor performance metrics
Master These Next
• Advanced Postman: Scripts, workflows
• Load testing with JMeter/k6
• API security (OWASP Top 10)
• GraphQL testing
• Continuous integration/deployment
Free Resources to Practice
• JSONPlaceholder: Fake API for testing
• PokéAPI: Real-world Pokemon API
• OpenWeatherMap: Weather API
• GitHub API: Test with real-world data
• Practice collection in Postman Hub
You're Now an API Testing Master!

From zero to hero in API testing fundamentals

Start testing real APIs today. You've got this!

Happy Testing!

You might also like