0% found this document useful (0 votes)
16 views30 pages

Comprehensive Guide to API Testing

The document serves as a comprehensive guide for API testing, covering essential topics from the basics to advanced techniques. It includes information on HTTP methods, status codes, various types of API testing, tools like Postman, and best practices for performance and security testing. Additionally, it provides practical scenarios and sample interview questions to aid in preparation for API testing roles.

Uploaded by

Jesila Foumiya
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)
16 views30 pages

Comprehensive Guide to API Testing

The document serves as a comprehensive guide for API testing, covering essential topics from the basics to advanced techniques. It includes information on HTTP methods, status codes, various types of API testing, tools like Postman, and best practices for performance and security testing. Additionally, it provides practical scenarios and sample interview questions to aid in preparation for API testing roles.

Uploaded by

Jesila Foumiya
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 Interview Guide

Basics to Advanced Preparation

Table of Contents
1. Introduction to API Testing
2. Fundamentals
3. HTTP Methods and Status Codes
4. Types of API Testing
5. API Testing Tools
6. Postman Basics
7. Request and Response Validation
8. Authentication and Security
9. Performance and Load Testing
10. Advanced Topics
11. Sample Interview Q&A
12. Practical Scenarios

Introduction to API Testing {#introduction}


API (Application Programming Interface) testing is a critical part of software testing that
focuses on validating the functionality, reliability, performance, and security of APIs.
Unlike UI testing, API testing operates at the application layer without the graphical
interface.

Why API Testing Matters


Speed: APIs are faster to test than UI
Reliability: Ensures system stability and data integrity
Security: Validates authentication and data protection
Performance: Measures response times and throughput
Cost-Effective: Requires fewer resources than UI testing

Fundamentals {#fundamentals}
What is an API?
An API is a set of protocols and tools that allows different software applications to
communicate and exchange data with each other. It acts as an intermediary layer between
applications.
Types of APIs
• REST API - Uses HTTP methods and is stateless
• SOAP API - Uses XML and is more complex
• GraphQL API - Allows clients to request specific data fields
• RPC API - Remote Procedure Call based communication
• WebSocket API - Enables real-time bidirectional communication

REST API Principles (IMPORTANT)


• Client-Server Architecture - Client and server are independent
• Statelessness - Each request contains all necessary information
• Cacheable - Responses should be cacheable when appropriate
• Uniform Interface - Consistent way of communicating
• Layered System - Architecture can have multiple layers
• Code on Demand - Optional capability to extend client functionality

Core Components of HTTP Request


Component Description
Method GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS
URL/Endpoint The resource address (e.g., /api/users)
Metadata about request (Content-Type,
Headers
Authorization)
Query
Additional data (e.g., ?page=1&limit=10)
Parameters
Body/Payload Request data (JSON, XML, Form Data)

Table 1: HTTP Request Components

Core Components of HTTP Response


Component Description
Status Code 2xx, 3xx, 4xx, 5xx responses
Headers Response metadata (Content-Type, Cache-Control)
Body Response data (usually JSON or XML)
Response Time Time taken to send the response

Table 2: HTTP Response Components


HTTP Methods and Status Codes {#http}
HTTP Methods (Verbs)
Method Purpose
Retrieve data from server (Safe &
GET
Idempotent)
Create new resource on server (Not
POST
idempotent)
PUT Update entire resource (Idempotent)
Partially update resource (Not
PATCH
idempotent)
Delete resource from server
DELETE
(Idempotent)
HEAD Like GET but without response body
OPTIONS Get allowed methods for a resource

Table 3: HTTP Methods

HTTP Status Codes


2xx - Success Codes
• 200 OK - Request succeeded, data returned
• 201 Created - Resource created successfully
• 202 Accepted - Request accepted for processing
• 204 No Content - Success but no content to return

3xx - Redirection Codes


• 301 Moved Permanently - Resource moved to new URL
• 302 Found - Temporary redirect
• 304 Not Modified - Cached response is valid
• 307 Temporary Redirect - Keep same method on redirect
4xx - Client Error Codes

• 400 Bad Request - Invalid request format or parameters


• 401 Unauthorized - Authentication required or invalid
• 403 Forbidden - User authenticated but not authorized
• 404 Not Found - Resource doesn't exist
• 409 Conflict - Request conflicts with current state
• 429 Too Many Requests - Rate limit exceeded
5xx - Server Error Codes
• 500 Internal Server Error - Server error occurred
• 501 Not Implemented - Functionality not implemented
• 502 Bad Gateway - Invalid response from upstream
• 503 Service Unavailable - Server temporarily unavailable
• 504 Gateway Timeout - Upstream server timeout

Key Differences: PUT vs PATCH


PUT PATCH
Replaces entire resource Partially updates resource
All fields must be sent Only changed fields sent
Idempotent Not necessarily idempotent
Used for full updates Used for partial updates

Table 4: PUT vs PATCH

Types of API Testing {#types}


1. Functional Testing
Validates that API functions as designed and returns correct results.
What to Test:
Correct response for valid inputs
Appropriate error messages for invalid inputs
Boundary value testing
Data validation
Error handling
Response structure and data types

2. Performance Testing
Measures API responsiveness, stability, and capacity under various load conditions.

Key Metrics:
Response time (latency)
Throughput (requests per second)
CPU and memory usage
Database query performance
Concurrent user handling
Types:

Load Testing - Normal expected load


Stress Testing - Beyond maximum capacity
Spike Testing - Sudden traffic increase
Endurance Testing - Sustained load over time
3. Security Testing
Ensures API protects against vulnerabilities and unauthorized access.
Areas to Cover:
Authentication and Authorization verification
Data encryption (HTTPS/TLS)
SQL Injection prevention
Cross-Site Scripting (XSS) prevention
CSRF protection
API key and token validation
Sensitive data exposure
Rate limiting and throttling

4. Reliability Testing
Verifies API can handle requests consistently without failures over time.
Testing Aspects:
Recovery from failures
Error handling consistency
Availability over time
Data integrity after failures

5. Validation Testing
Confirms API returns expected results and follows correct protocols.

Validation Points:
Response data accuracy
Data format compliance (JSON schema)
Header validation
Content-Type verification
Response body structure

6. Integration Testing
Ensures different API components and external systems work together correctly.
Testing Focus:

Database integration
Third-party API integration
Service-to-service communication
Data flow between systems
Dependency handling
7. End-to-End (E2E) Testing
Tests complete workflow simulating real user scenarios.
Scope:
Multi-step workflows
Data persistence across requests
System state management
External system dependencies

8. Compatibility/Interoperability Testing
Verifies API works across different devices, platforms, and systems.
Check Points:
Different client platforms
Various browsers (if applicable)
Mobile vs web clients
Legacy system compatibility
Version compatibility

9. Documentation Testing
Validates API documentation is accurate, complete, and helpful.

Review Areas:
Endpoint descriptions accuracy
Request/response examples correctness
Error code documentation
Parameter documentation
Authentication method documentation
Sample code accuracy

API Testing Tools {#tools}


Popular API Testing Tools
Tool Features Best For
GUI, Collections, Manual &
Postman Scripting, Automation Automated
Testing
SOAP & REST, SOAP APIs,
SoapUI Complex testing, Complex
Mocking scenarios
Load testing, Performance
JMeter Performance, & Load
Scalability Testing
Complete testing, End-to-end
Katalon Studio
Cloud execution automation
Simple, Lightweight, Manual API
Insomnia
Intuitive testing
Java library, BDD Java-based
REST Assured
support, Open source automation
Command-line, Quick
cURL Lightweight, testing,
Debugging Debugging
API management, API
Analytics, Monitoring management
Apigee
&
monitoring
No-code, Visual, Enterprise
Tricentis Tosca
Enterprise solution automation

Table 5: API Testing Tools Comparison

When to Use Each Tool


Postman: Best for QA engineers starting API testing or doing manual testing
REST Assured: Best for automation engineers using Java
JMeter: Best for performance and load testing
SoapUI: Best for SOAP API testing or complex scenarios
cURL: Best for quick debugging and terminal-based testing
Postman Basics {#postman-basics}
Postman Essentials
What is Postman?
Postman is a comprehensive API development and testing platform. It provides both GUI
and command-line tools for API testing, automation, and collaboration.

Key Postman Features


• Request Builder - Easy GUI for creating HTTP requests
• Collections - Organize requests into logical groups
• Environments - Store variables for different environments (dev, staging, prod)
• Test Scripts - Write JavaScript code to validate responses
• Pre-request Scripts - Execute code before sending request
• Mock Servers - Create fake APIs for testing
• Postman Console - Debug requests and responses
• Newman - Command-line tool for running Postman collections
• API Documentation - Auto-generate documentation
• Monitoring - Monitor API health continuously
• Workspace Collaboration - Share collections with team

Creating a Request in Postman


Step-by-Step Process:

1. Select HTTP method (GET, POST, etc.)


2. Enter the endpoint URL
3. Add Headers (Content-Type, Authorization, etc.)
4. Add Query Parameters if needed
5. Add Body data (for POST, PUT, PATCH)
6. Click Send
7. Analyze response status, headers, and body
8. Add tests to validate response

Postman Collections
Collections are folders that organize related requests together.
Benefits:
Group related tests
Share with team members
Run entire test suite at once
Version control testing scenarios
Maintain test documentation
Environment Variables in Postman
Variables allow reusing values across multiple requests.
Types of Variables:
• Global variables - Available across all collections
• Environment variables - Available within specific environment
• Collection variables - Available within collection
• Local variables - Available within specific request

Example:
{{base_url}}/api/users
{{token}}
{{user_id}}

Postman Test Scripts


JavaScript code to validate API responses automatically.
Example Test Script:

// Validate status code


[Link]("Status code is 200", function () {
[Link](200);
});
// Validate response body
[Link]("Response contains user data", function () {
var jsonData = [Link]();
[Link](jsonData.user_id).[Link];
[Link]([Link]).[Link]("@");
});
// Validate headers
[Link]("Response has Content-Type header", function () {
[Link]("Content-Type");
});

// Set variable from response


[Link]("user_token", [Link]().token);

Newman - Command Line Runner


Newman is Postman's command-line tool for running collections.
Commands:
Run basic collection
newman run [Link]

Run with environment


newman run [Link] -e [Link]

Generate HTML report


newman run [Link] --reporters html

Run with specific variables


newman run [Link] --global-var "api_key=xyz123"

Run collection multiple times


newman run [Link] --iterations 5

Request and Response Validation {#validation}


Validating HTTP Status Codes
Always verify correct status codes are returned.
Validation Checklist:
• GET existing resource → 200 OK
• POST create resource → 201 Created
• PUT update resource → 200 OK
• DELETE resource → 200 OK or 204 No Content
• Invalid request → 400 Bad Request
• Unauthorized → 401 Unauthorized
• Forbidden → 403 Forbidden
• Not found → 404 Not Found
• Server error → 500 Internal Server Error

Validating Response Headers


Header What to Validate
Content-Type Should be application/json for JSON APIs
Content-Length Should match response body size
Authorization Present and valid for protected endpoints
Cache-Control Appropriate caching strategy
CORS Headers Correct for cross-origin requests
Set-Cookie Secure flag set for sensitive cookies

Table 6: Important Response Headers

Validating Response Body


Data Type Validation:
Ensure response contains correct data types (string, number, boolean, array, object).

Schema Validation:
Validate response matches expected JSON schema.
Field Presence Validation:

Verify all expected fields are present in response.


Value Range Validation:
Check numeric values are within expected ranges.

Format Validation:
Verify email, date, URL formats are correct.
Boundary Value Testing:

Test edge cases:


Maximum length strings
Minimum and maximum numbers
Empty values
Null values

Testing Different Content Types


Postman supports testing APIs with different content types:
• application/json
• application/xml
• text/html
• text/plain
• application/x-www-form-urlencoded
• multipart/form-data
Authentication and Security {#auth-security}
Authentication Types
Method Description
Simple token sent in header or
API Key
query parameter
Username and password
Basic Auth
encoded in Base64
Token sent in Authorization
Bearer Token
header
Complex token-based
OAuth 2.0
authentication framework
JSON Web Token containing
JWT
encoded claims
Hash-based authentication for
Digest Auth
HTTP

Table 7: Authentication Methods

API Key Testing


Test Cases:
Valid API key returns successful response
Missing API key returns 401 Unauthorized
Invalid API key returns 401 or 403
Expired API key returns 401
API key in different locations (header, query, body)

JWT Testing
JWT Structure: [Link]
Test Cases:

Valid JWT grants access


Expired JWT returns 401
Invalid signature returns 401
Missing JWT returns 401
Tampered JWT returns 401
OAuth 2.0 Testing
Grant Types to Test:
• Authorization Code - Web applications
• Implicit - JavaScript applications
• Resource Owner Password - Legacy applications
• Client Credentials - Service-to-service

Security Vulnerability Testing


• SQL Injection - Try payloads: ' OR '1'='1, admin'--
• XSS (Cross-Site Scripting) - Try: <script>alert('XSS')</script>
• CSRF - Verify anti-CSRF tokens present
• Rate Limiting - Test endpoint with excessive requests
• Data Exposure - Verify sensitive data encrypted in transit
• Broken Access Control - Test authorization for different user roles
• Input Validation - Try oversized payloads, special characters

HTTPS and SSL/TLS Testing


Always verify APIs use HTTPS in production.

Test Points:
HTTPS enabled (no HTTP allowed)
Valid SSL certificate
Certificate not expired
Secure headers present
No mixed content (HTTPS page with HTTP resources)

Performance and Load Testing {#performance}


Performance Testing Metrics
Metric Definition
Response Time Time from request sent to response received
Throughput Requests processed per second
Error Rate Percentage of failed requests
CPU Usage Processor utilization during load
Memory Usage RAM consumption under load
Database Query Time Backend processing time

Table 8: Performance Metrics


Load Testing with JMeter
Basic Steps:
1. Define Thread Group (number of users, ramp-up time)
2. Add HTTP Request Sampler
3. Add Listeners for results
4. Run test and analyze results
JMeter Components:

• Thread Group - Virtual users


• HTTP Request - API call
• Assertion - Validation
• Listener - Results visualization
• Config Element - Shared settings

Performance Testing Best Practices


• Test against production-like infrastructure
• Run baseline test first
• Gradually increase load (ramping)
• Monitor server resources during testing
• Test during different times and scenarios
• Use realistic data for testing
• Document expected vs actual results
• Identify bottlenecks and optimize
• Retest after optimizations

Response Time Optimization


Common Bottlenecks:
Slow database queries
External API calls
Large payload processing
Inefficient algorithms
Missing caching

Optimization Techniques:
Database indexing
Query optimization
Caching mechanisms
Pagination for large datasets
Asynchronous processing
Advanced Topics {#advanced}
API Versioning Strategies
Strategy Example
URL Path /api/v1/users, /api/v2/users
Query Parameter /api/users?version=1
Accept:
Header Based
application/[Link]+json;version=1
[Link] vs
Subdomain
[Link]

Table 9: API Versioning Approaches

Backward Compatibility Testing


Test Cases:
Old clients can use old API version
New features in new version don't break old clients
Deprecation warnings shown appropriately
Migration path from old to new version clear

Rate Limiting and Throttling


Test Cases:
Requests within limit → 200 OK
Requests exceeding limit → 429 Too Many Requests
Rate limit headers present in response
Rate limit resets at correct interval
Burst requests handled correctly

Rate Limiting Headers:


X-RateLimit-Limit
X-RateLimit-Remaining
X-RateLimit-Reset
Retry-After

API Pagination Testing


Test Cases:
Page parameter works correctly
Limit parameter restricts results
Total count accurate
Last page identified correctly
Out of range pages handled
Default values applied if not specified
Common Pagination Parameters:
page, page_size / limit, offset
start, count
cursor (cursor-based pagination)

Caching Strategies
• Browser Cache - Controlled by Cache-Control header
• Server Cache - Redis, Memcached
• CDN Cache - Content delivery networks
• Database Cache - Query result caching

Cache Headers:
Cache-Control: max-age=3600
ETag: Unique resource identifier
Last-Modified: Last modification time
Expires: Absolute expiration time

Handling Asynchronous APIs


Challenge: API returns immediately with status URL for result checking.

Test Approach:
1. Send async request
2. Get response with status URL
3. Poll status URL periodically
4. Verify final result when ready
5. Test timeout scenarios

Testing Webhook Integration


Test Approach:
1. Set up local webhook endpoint
2. Configure API to send events to endpoint
3. Trigger events in API
4. Verify webhook receives correct data
5. Test retry mechanisms
6. Test webhook signature validation

Error Message Testing


• Error codes are meaningful and documented
• Error messages are user-friendly
• Error responses have consistent structure
• Error details help debugging
• Sensitive information not exposed in errors
• Internationalization (multiple languages) if applicable
Testing With Data-Driven Scenarios
Use external data sources (CSV, Excel, JSON) to run multiple test cases.
Benefits:
Test multiple scenarios with one test
Easy to maintain test data
Comprehensive coverage
Easier to identify patterns in failures

Sample Interview Q&A {#qa}


Beginner Level Questions
Q1: What is API Testing?

Ans: API testing is a type of software testing that focuses on validating the functionality,
reliability, and security of APIs without a graphical user interface. It tests the business logic
layer of the application using various API testing tools and techniques. Unlike UI testing,
API testing is faster and more reliable because it operates at the application layer.
Q2: What is the difference between API and UI testing?
Ans:

Speed: API testing is faster; UI testing takes more time


Coverage: API tests can cover more scenarios
Cost: API testing is more cost-effective
Reliability: API tests are more stable than UI tests
Debugging: API errors are easier to debug
Tool Requirements: Different tools required
User Experience: UI testing focuses on user experience; API testing focuses on data
and logic
Q3: Name the core components of HTTP request.
Ans: The core components of an HTTP request are:

Method (GET, POST, PUT, DELETE, PATCH)


URL/Endpoint
Headers (metadata)
Query Parameters
Request Body (for POST, PUT, PATCH)
Q4: What are HTTP status codes?
Ans: HTTP status codes are three-digit responses that indicate the outcome of HTTP
requests:

2xx (200-299): Success - Request succeeded


3xx (300-399): Redirection - Further action needed
4xx (400-499): Client Error - Invalid request
5xx (500-599): Server Error - Server failed to fulfill valid request
Q5: What is the difference between GET and POST?

Ans:
GET: Retrieves data, no body, idempotent, can be cached, visible in URL
POST: Creates data, has body, not idempotent, not cached, data in body (hidden)

Intermediate Level Questions


Q6: What is REST API?
Ans: REST (Representational State Transfer) is an architectural style for designing
networked applications. It uses HTTP requests to perform CRUD operations. Key principles:

Client-Server architecture
Statelessness
Uniform Interface
Resource-based URLs
Uses standard HTTP methods
Cacheable responses
Q7: Explain the difference between PUT and PATCH.
Ans:

PUT: Replaces entire resource. All fields must be provided. Idempotent (multiple calls
produce same result).
PATCH: Partially updates resource. Only changed fields needed. Not necessarily
idempotent.
Q8: What are the different types of API testing?
Ans: Different types of API testing include:

Functional Testing - Validates functionality


Performance Testing - Measures speed and stability
Security Testing - Validates against vulnerabilities
Reliability Testing - Tests consistent behavior
Integration Testing - Tests component interaction
End-to-End Testing - Tests complete workflows
Compatibility Testing - Tests across platforms
Q9: What is the use of Postman Pre-request Script?
Ans: Pre-request Scripts in Postman run before sending the request. Uses:

Generate dynamic data


Set up variables
Modify request parameters
Call setup functions
Generate timestamps
Create authorization tokens
Example:
var timestamp = new Date().getTime();
[Link]("timestamp", timestamp);
Q10: How would you test a POST request in Postman?

Ans:
1. Select POST method
2. Enter endpoint URL
3. Add Content-Type header (application/json)
4. Add request body in JSON format
5. Send request
6. Verify status code (201 Created)
7. Validate response body
8. Add test scripts to automate validation
Q11: What is JSONPath and how is it used in API testing?

Ans: JSONPath is a query language to extract and validate specific values from JSON
responses. It works like XPath for XML.
Common JSONPath Syntax:
$.field - Access root field
$.[Link] - Access nested field
$[0] - Access array element
$.items[*].id - Get all IDs from items array
$..email - Recursively find email at any level

Example in Postman:
var jsonData = [Link]();
var userId = [Link][0].user_id;
[Link]("user_id", userId);
Q12: What is Request Specification in REST Assured?
Ans: RequestSpecification in REST Assured is used to define common request attributes that
apply to multiple requests. It reduces code duplication and improves maintainability.

Example:
RequestSpecification request = [Link]()
.baseUri("[Link]
.header("Content-Type", "application/json")
.auth().basic("username", "password");
Response response = [Link]("/users");
Benefits:

Reusable configuration
Consistent request setup
Easy maintenance
Less code repetition
Q13: How do you validate JSON schema in REST Assured?
Ans: JSON Schema validation ensures response structure matches expected format. You
need json-schema-validator dependency.

Example:
[Link]()
.get("/api/users")
.then()
.statusCode(200)
.body(matchesJsonSchemaInClasspath("[Link]"));
Schema File ([Link]):
{
"type": "object",
"properties": {
"id": { "type": "number" },
"name": { "type": "string" },
"email": { "type": "string" }
},
"required": ["id", "name", "email"]
}
Q14: What is the difference between Headers and Header class in REST Assured?

Ans:
Header (Singular): Represents a single header key-value pair
Headers (Plural): Collection of multiple headers
Example:
// Single Header
Header contentType = new Header("Content-Type", "application/json");

// Multiple Headers
Headers headers = new Headers(
new Header("Content-Type", "application/json"),
new Header("Authorization", "Bearer token123"),
new Header("Accept", "application/json")
);
[Link]().headers(headers).get("/api/endpoint");
Q15: How do you handle timeouts in REST Assured?

Ans: Timeouts prevent tests from hanging indefinitely on slow or unresponsive servers.
Example:
[Link]()
.config([Link]().httpClient(
[Link]()
.setParam(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000)
.setParam(CoreConnectionPNames.SO_TIMEOUT, 10000)
))
.get("/api/endpoint")
.then()
.statusCode(200);
Timeout Types:

Connection Timeout - Wait for connection establishment


Socket Timeout - Wait for data from server
Request Timeout - Total time for request/response

Advanced Level Questions


Q16: What is OAuth 2.0 and what are its grant types?
Ans: OAuth 2.0 is an authorization framework that allows secure delegated access without
sharing passwords.
Grant Types:

1. Authorization Code - Web applications


User clicks "Login with Google"
Redirected to OAuth provider
Provider returns authorization code
Code exchanged for token
2. Implicit - JavaScript/SPA applications
Direct token returned from authorization endpoint
No backend server needed
3. Resource Owner Password Credentials - Legacy/trusted apps
User enters username/password to app
App sends to authorization server
4. Client Credentials - Service-to-service authentication
Direct token exchange using client ID and secret
Q17: How do you extract and chain values across multiple API requests?
Ans: Chaining requests allows using response from one request as input to another. This is
essential for multi-step workflows.

Example in Postman:
// First request - Login
POST /api/login
Body: {"username": "test", "password": "pass123"}
// In Tests tab - Extract token
var jsonData = [Link]();
[Link]("auth_token", [Link]);
// Second request - Get User Details
GET /api/users/me
Header: Authorization: Bearer {{auth_token}}

// In Tests tab - Extract user ID


var userId = [Link]().id;
[Link]("user_id", userId);
// Third request - Update User
PUT /api/users/{{user_id}}
Body: {"name": "Updated Name"}
Header: Authorization: Bearer {{auth_token}}
Q18: What is data-driven testing in API testing and how do you implement it?

Ans: Data-driven testing uses external data sources (CSV, Excel, JSON) to test multiple
scenarios with different input values.
Benefits:
Test multiple scenarios with one test
Easy to add new test cases
Separate test logic from test data
Better coverage and maintainability

Example with CSV in Postman:


// CSV File (test_data.csv)
username,email,expected_status
john_doe,john@[Link],201
jane_smith,jane@[Link],201
invalid_user,invalid_email,400
// Collection Runner
1. Import CSV file
2. Run collection for each row
3. Use {{username}}, {{email}} variables
4. Validate {{expected_status}}

Q19: How do you test APIs for security vulnerabilities?


Ans: Security testing validates API protection against attacks and unauthorized access.
Test Cases:

1. SQL Injection:
POST /api/users
Body: {"username": "' OR '1'='1"}
Verify: Returns 400 or sanitized response
2. XSS (Cross-Site Scripting):
POST /api/posts
Body: {"title": "alert('XSS')"}
Verify: Script is escaped or removed
3. Authentication Bypass:
GET /api/admin/users
(Without Authorization header)
Verify: Returns 401 Unauthorized
4. CSRF Protection:
POST /api/delete-account
(Without CSRF token)
Verify: Returns 403 Forbidden
5. Sensitive Data Exposure:
GET /api/users/123
Verify: Password and sensitive fields not in response
6. Rate Limiting:
Send 100 requests in rapid succession
Verify: Returns 429 Too Many Requests
Q20: What is the Collection Runner and how do you use it?

Ans: Collection Runner in Postman executes all requests in a collection sequentially,


allowing data-driven testing and generating reports.
How to Use:
1. Click "Runner" button in Postman
2. Select Collection to run
3. Choose Environment
4. Select data file (CSV/JSON) if needed
5. Set iterations count
6. Click "Run Collection"
7. View results and generate report

Benefits:
Run multiple requests in sequence
Data-driven testing support
Automated test execution
Generate HTML/JSON reports
Identify failing tests quickly
Q21: How do you handle API responses with different content types?

Ans: APIs can return different content types (JSON, XML, HTML, etc.). Testing must validate
the correct content type.
Example:
// Get JSON response
GET /api/users
Accept: application/json
// Get XML response
GET /api/users
Accept: application/xml

// Validate in Postman
[Link]("Check Content-Type is JSON", function() {
[Link]("Content-Type", "application/json");
});
Common Content Types:
application/json
application/xml
text/plain
text/html
application/x-www-form-urlencoded
multipart/form-data
Q22: What are edge cases in API testing and how do you test them?

Ans: Edge cases are unusual or extreme situations at boundaries of input ranges. Testing
them reveals hidden bugs.
Common Edge Cases:
1. Empty/Null Values:
POST /api/users
Body: {"name": null, "email": ""}
Verify: Proper validation error message
2. Boundary Values:
POST /api/posts
Body: {"length": 0, "length": 999999}
Verify: Both handled correctly
3. Special Characters:
POST /api/search
Body: {"query": "@#$%^&*()"}
Verify: Proper encoding and handling
4. Duplicate Data:
POST /api/users
Body: {"email": "existing@[Link]"}
Verify: Returns 409 Conflict
5. Concurrent Requests:
Send same request 10 times simultaneously
Verify: Database consistency maintained
6. Large Payloads:
POST /api/upload
Body: 500MB file
Verify: Proper rejection or handling

Q23: How do you implement BDD (Behavior Driven Development) in API testing?
Ans: BDD uses human-readable scenarios to define test cases, making tests more
maintainable and understandable.
Tools: Cucumber + REST Assured

Feature File ([Link]):


Feature: User Management API
Scenario: Create new user with valid data
Given I have user data with name "John" and email "john@[Link]"
When I send POST request to "/api/users"
Then the response status should be 201
And the response body should contain user ID
Scenario: Handle duplicate user creation
Given a user already exists with email "john@[Link]"
When I attempt to create user with same email
Then the response status should be 409
And the error message should be "User already exists"
Step Definition (Java):
@Given("I have user data with name {string} and email {string}")
public void prepareUserData(String name, String email) {
[Link]("name", name);
[Link]("email", email);
}

@When("I send POST request to {string}")


public void sendPostRequest(String endpoint) {
response = [Link]()
.body(userData)
.post(endpoint);
}
@Then("the response status should be {int}")
public void verifyStatusCode(int statusCode) {
[Link]([Link](), statusCode);
}
Q24: What are the best practices for API test automation?

Ans: Best practices ensure reliable, maintainable, and efficient API testing.
Key Practices:
1. Modular Test Structure:
Separate test logic from test data
Use base test classes
Create utility methods
2. Proper Assertion Strategy:
Test one thing per test
Use meaningful assertion messages
Verify response status, headers, and body
3. Dependency Management:
Handle test data setup/cleanup
Use pre-request scripts for setup
Clean up after tests (delete created data)
4. Environment Management:
Use environment variables
Separate dev, staging, prod configs
Never hardcode URLs or credentials
5. Reporting and Logging:
Generate detailed test reports
Log requests and responses
Use reporting tools (ExtentReports, Allure)
6. CI/CD Integration:
Run tests in pipeline
Fail build on test failure
Generate test metrics
7. Performance Considerations:
Monitor response times
Test with realistic data volumes
Profile slow endpoints
Q25: How do you debug API test failures?

Ans: Effective debugging helps quickly identify and fix test failures.
Debugging Techniques:
1. Enable Logging:
[Link]();
[Link]()
.log().all() // Log request
.get("/api/endpoint")
.then()
.log().all(); // Log response
2. Use Postman Console:
Send request in Postman
Open Console (bottom-left)
View full request/response details
3. Print Response Body:
String responseBody = [Link]().prettyPrint();
[Link](responseBody);
4. Check Status Code:
[Link]("Status: " + [Link]());
[Link]("Headers: " + [Link]());
5. Validate Response Structure:
[Link]("Response body should have all fields", function() {
var jsonData = [Link]();
[Link]([Link](jsonData, null, 2));
});
6. Compare Expected vs Actual:
Expected: {"id": 1, "name": "John", "email": "john@[Link]"}
Actual: Response from API
Difference: Identify mismatch

Practical Scenarios {#scenarios}


Scenario 1: Testing User Creation API
Endpoint: POST /api/v1/users
Request:
{
"first_name": "John",
"last_name": "Doe",
"email": "john@[Link]",
"password": "SecurePassword123"
}
Test Cases:

1. Positive Test: Valid data creates user


Verify: 201 status code
Verify: User ID in response
Verify: Email matches request
2. Negative Test: Duplicate email
Send existing email
Verify: 409 Conflict
Error message present
3. Validation Test: Invalid email format
Send invalid email
Verify: 400 Bad Request
Error message specifies email issue
4. Security Test: SQL injection attempt
Send: email: "'; DROP TABLE users;--"
Verify: 400 Bad Request (not executed)
Data integrity maintained

Scenario 2: Testing User Authentication API


Endpoint: POST /api/v1/auth/login
Test Cases:
1. Valid Credentials: Correct username and password
Verify: 200 OK
Verify: JWT token in response
Verify: Token is valid
2. Invalid Password: Wrong password
Verify: 401 Unauthorized
Verify: No token returned
Account not locked
3. User Not Found: Non-existent user
Verify: 404 Not Found
Verify: Generic error message
4. Brute Force: Multiple failed attempts
Verify: Rate limiting engaged
Verify: Account temporarily locked

Scenario 3: Testing Data Retrieval with Pagination


Endpoint: GET /api/v1/users?page=1&limit=10
Test Cases:
1. First Page: Retrieve first 10 records
Verify: 200 OK
Verify: 10 records returned
Verify: Has next page indicator
2. Last Page: Navigate to last page
Verify: Fewer than 10 records
Verify: No next page indicator
3. Invalid Page: Non-existent page
Verify: 404 or empty array
Verify: Appropriate error message
4. Large Limit: Request more than max
Verify: Capped at maximum
Verify: Warning in response

Scenario 4: Testing API Rate Limiting


Endpoint: Any endpoint
Test Cases:

1. Within Limit: Normal requests


Verify: 200 OK
Verify: Rate limit headers present
2. Exceed Limit: Too many requests
Verify: 429 Too Many Requests
Verify: Retry-After header
3. Rate Limit Reset: Wait for reset
Verify: Can make requests again
Verify: Counter reset

Interview Preparation Tips


Before Your Interview
1. Research the company's API and tech stack
2. Practice with Postman and other tools
3. Be ready to explain your testing approach
4. Review API documentation standards
5. Prepare questions about the role
6. Practice explaining technical concepts clearly
7. Mock interview with peers
8. Prepare examples from your projects

During Your Interview


1. Listen carefully to questions
2. Ask clarifying questions
3. Provide specific examples
4. Explain your reasoning
5. Mention tools and best practices
6. Show enthusiasm for testing
7. Discuss security concerns
8. Ask about challenges they face
Common Interview Mistakes to Avoid
• Not explaining your test approach
• Forgetting to mention security testing
• Not knowing basic HTTP concepts
• Not being familiar with at least one tool
• Overlooking edge cases in scenarios
• Not discussing performance testing
• Forgetting documentation testing
• Not mentioning error handling
• Being unfamiliar with JSON/XML

Key Takeaways
• Master HTTP basics - methods, status codes, headers
• Learn at least one tool thoroughly (Postman recommended)
• Understand different testing types and when to apply them
• Know authentication mechanisms (API Keys, JWT, OAuth)
• Be familiar with performance and security testing
• Practice writing test cases and validation scripts
• Understand REST principles and best practices
• Know how to handle edge cases and error scenarios
• Stay updated with latest API testing trends
• Prepare real-world examples from your experience

References
[1] GeeksforGeeks. (2023). API Testing Interview Questions And Answers - 2025. [Link]
[Link]/software-testing/api-testing-interview-questions/
[2] TestLeaf. (2025). Top 60+ API Testing Interview Questions 2025. [Link]
blog/top-60-api-testing-interview-questions-for-fresher-to-experience-2025/
[3] Simplilearn. (2025). Top 50 API Testing Interview Questions and Answers (2025). [Link]
[Link]/top-api-testing-interview-questions-article

[4] Katalon. (2018). Top 50+ API Testing Interview Questions [Free Template]. [Link]
com/resources-center/blog/web-api-testing-interview-questions
[5] testRigor. (2025). Top 25 API Testing Interview Questions. [Link]
ting-interview-questions/
[6] Final Round AI. (2024). REST API Interview Questions. [Link]
g/rest-api-interview-questions

[7] Final Round AI. (2024). Postman Interview Questions. [Link]


g/postman-interview-questions
[8] Adaface. (2024). 98 API Testing interview questions. [Link]
sting-interview-questions/
[9] Browserless. (2025). REST API Interview Questions 2025. [Link]
rest-api-interview-questions-answers-2025
[10] Software Testing Material. (2025). 30+ Postman Interview Questions & Answers. https://
[Link]/postman-interview-questions/

[11] Simplilearn. (2025). 60+ Top Postman Interview Questions & Answers for 2025. [Link]
[Link]/postman-interview-questions-answers-article
[12] Rahul Shetty Academy. (2023). API Testing Interview Questions. [Link]
[Link]/blog/[Link]/api-testing-interview-questions/
[13] Merge. (2024). 10 critical REST API interview questions for 2025—answered. [Link]
[Link]/blog/rest-api-interview-questions

[14] Frugal Testing. (2025). Top 40 Rest Assured Interview Questions. [Link]
[Link]/blog/master-your-next-interview-top-40-rest-assured-interview-questions-and-expert
-answers

You might also like