
API Testing Interview Questions: REST, Postman, and Automation
API testing is a critical skill for modern QA engineers. With microservices architectures and API-first development, the ability to test APIs effectively is more valuable than ever. This guide covers questions from basic concepts to advanced automation scenarios.
Table Of Contents-
API Fundamentals
Q: What is an API?
Answer: API (Application Programming Interface) is a contract that defines how software components communicate. It specifies:
- What requests can be made
- What data format to use
- What responses to expect
- What errors might occur
Types of APIs:
| Type | Description | Use Case |
|---|---|---|
| REST | Stateless, HTTP-based | Web services, mobile backends |
| GraphQL | Query language, single endpoint | Flexible data fetching |
| SOAP | XML-based, strict contract | Enterprise, legacy systems |
| gRPC | Binary protocol, high performance | Microservices, internal |
Q: What is API testing and why is it important?
Answer:
API testing validates that APIs:
- Return correct data
- Handle errors appropriately
- Perform acceptably under load
- Are secure from attacks
- Follow the specification
Why it's important:
- Early detection: Find bugs before UI is built
- Speed: Faster than UI testing
- Reliability: Less flaky than UI tests
- Coverage: Test business logic directly
- Integration: Validate system communication
What to test:
- Functionality (correct responses)
- Error handling (graceful failures)
- Performance (response times)
- Security (authentication, authorization)
- Data validation (input/output)
Q: What's the difference between API testing and UI testing?
Answer:
| Aspect | API Testing | UI Testing |
|---|---|---|
| Layer | Business logic | Presentation |
| Speed | Fast (no rendering) | Slower (browser rendering) |
| Stability | More stable | More flaky |
| Maintenance | Lower | Higher |
| User perspective | Technical | End-user |
| Coverage | Internal logic | User workflows |
| Tools | Postman, REST Assured | Selenium, Playwright |
Both are needed: API tests for comprehensive logic coverage, UI tests for user experience validation.
HTTP and REST Concepts
Q: What are HTTP methods and when do you use each?
Answer:
| Method | Purpose | Idempotent | Safe |
|---|---|---|---|
| GET | Retrieve resource | Yes | Yes |
| POST | Create resource | No | No |
| PUT | Replace resource | Yes | No |
| PATCH | Partial update | No | No |
| DELETE | Remove resource | Yes | No |
| HEAD | Get headers only | Yes | Yes |
| OPTIONS | Get allowed methods | Yes | Yes |
Idempotent: Same request multiple times = same result Safe: Doesn't modify resources
Examples:
GET /users/123 - Retrieve user 123
POST /users - Create new user
PUT /users/123 - Replace user 123 completely
PATCH /users/123 - Update specific fields of user 123
DELETE /users/123 - Delete user 123Q: What are HTTP status codes and their meanings?
Answer:
1xx - Informational:
- 100 Continue
- 101 Switching Protocols
2xx - Success:
- 200 OK - Request succeeded
- 201 Created - Resource created
- 204 No Content - Success, no body
3xx - Redirection:
- 301 Moved Permanently
- 302 Found (temporary redirect)
- 304 Not Modified (cached)
4xx - Client Errors:
- 400 Bad Request - Invalid syntax
- 401 Unauthorized - Authentication required
- 403 Forbidden - Permission denied
- 404 Not Found - Resource doesn't exist
- 405 Method Not Allowed
- 409 Conflict - State conflict
- 422 Unprocessable Entity - Validation failed
- 429 Too Many Requests - Rate limited
5xx - Server Errors:
- 500 Internal Server Error
- 502 Bad Gateway
- 503 Service Unavailable
- 504 Gateway Timeout
Q: What is REST and what are its principles?
Answer:
REST (Representational State Transfer) is an architectural style with these constraints:
1. Client-Server: Separation of concerns 2. Stateless: Each request contains all needed information 3. Cacheable: Responses should define cacheability 4. Uniform Interface: Consistent resource identification and manipulation 5. Layered System: Client doesn't know if talking directly to server 6. Code on Demand (optional): Server can send executable code
RESTful API characteristics:
- Resources identified by URIs
- Standard HTTP methods
- Multiple representations (JSON, XML)
- HATEOAS (hypermedia links in responses)
Q: What is the difference between PUT and PATCH?
Answer:
PUT - Complete replacement:
// Current user:
{ "id": 1, "name": "John", "email": "john@example.com", "age": 30 }
// PUT /users/1 with:
{ "name": "Jane" }
// Result:
{ "id": 1, "name": "Jane" }
// email and age are removed!PATCH - Partial update:
// Current user:
{ "id": 1, "name": "John", "email": "john@example.com", "age": 30 }
// PATCH /users/1 with:
{ "name": "Jane" }
// Result:
{ "id": 1, "name": "Jane", "email": "john@example.com", "age": 30 }
// Only name changed, other fields preservedPUT is idempotent (same request = same result). PATCH is not necessarily idempotent depending on implementation.
Request and Response
Q: What are the components of an HTTP request?
Answer:
POST /api/users HTTP/1.1
Host: api.example.com
Content-Type: application/json
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
Accept: application/json
{
"name": "John Doe",
"email": "john@example.com"
}Components:
| Component | Description | Example |
|---|---|---|
| Method | HTTP verb | POST |
| URI | Resource path | /api/users |
| Headers | Metadata | Content-Type, Authorization |
| Body | Request payload | JSON data |
| Query params | URL parameters | ?page=1&limit=10 |
Q: What are common HTTP headers and their purposes?
Answer:
Request headers:
Content-Type: Format of request body (application/json)Accept: Expected response formatAuthorization: Authentication credentialsUser-Agent: Client identificationCache-Control: Caching directives
Response headers:
Content-Type: Format of response bodyContent-Length: Size of responseCache-Control: Caching instructionsSet-Cookie: Cookies to storeLocation: Redirect URL (with 3xx)
Custom headers:
X-Request-ID: Request tracingX-Rate-Limit-Remaining: API rate limits
Q: What is JSON and how do you validate it?
Answer:
JSON (JavaScript Object Notation) is a lightweight data format:
{
"string": "value",
"number": 123,
"boolean": true,
"null": null,
"array": [1, 2, 3],
"object": {
"nested": "value"
}
}Validation approaches:
1. Schema validation (JSON Schema):
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": ["id", "name"],
"properties": {
"id": { "type": "integer" },
"name": { "type": "string", "minLength": 1 },
"email": { "type": "string", "format": "email" }
}
}2. Field-by-field validation:
- Check required fields exist
- Validate data types
- Verify value constraints
- Check nested structures
3. Contract testing:
- Consumer expectations match provider output
Authentication and Security
Q: What are common API authentication methods?
Answer:
1. API Key:
GET /api/data HTTP/1.1
X-API-Key: abc123def456- Simple, static key
- Sent in header or query param
- Good for public APIs with rate limiting
2. Basic Authentication:
GET /api/data HTTP/1.1
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=- Base64 encoded username:password
- Must use HTTPS
- Simple but less secure
3. Bearer Token (JWT):
GET /api/data HTTP/1.1
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...- Token obtained via login
- Self-contained (claims)
- Expiration handling needed
4. OAuth 2.0:
- Token obtained via authorization flow
- Supports different grant types
- Standard for third-party access
5. Mutual TLS:
- Both client and server certificates
- Strong authentication
- Complex setup
Q: How do you test API security?
Answer:
Authentication testing:
- Missing credentials → 401
- Invalid credentials → 401
- Expired token → 401
- Correct credentials → 200
Authorization testing:
- User A accessing User B's data → 403
- Unauthorized role accessing admin endpoint → 403
- Correct role → 200
Input validation:
- SQL injection:
' OR 1=1 -- - XSS payloads:
<script>alert('xss')</script> - Path traversal:
../../etc/passwd - Large payloads (size limits)
Security headers:
- CORS configuration
- Content-Security-Policy
- X-Content-Type-Options
Rate limiting:
- Verify limits are enforced
- Test limit reset behavior
Q: What is a JWT and how do you test APIs using JWT?
Answer:
JWT (JSON Web Token) has three parts:
header.payload.signatureExample:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4iLCJpYXQiOjE1MTYyMzkwMjJ9.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5cHeader: Algorithm and type Payload: Claims (user data, expiration) Signature: Verification
Testing with JWT:
- Obtain token:
POST /auth/login
{ "username": "user", "password": "pass" }
→ { "token": "eyJhbG..." }- Use token:
GET /api/protected
Authorization: Bearer eyJhbG...- Test scenarios:
- Valid token → success
- Expired token → 401
- Tampered token → 401
- Missing token → 401
- Token for different user → 403
API Testing Approaches
Q: What test cases would you write for a REST API?
Answer:
For POST /api/users:
Positive tests:
- Valid data → 201 Created
- All optional fields → 201 Created
- Minimum required fields → 201 Created
Negative tests:
- Missing required fields → 400/422
- Invalid email format → 400/422
- Duplicate email → 409 Conflict
- Invalid data types → 400
- Empty body → 400
Security tests:
- Without authentication → 401
- With invalid token → 401
- SQL injection in fields → Rejected/sanitized
Boundary tests:
- Maximum length strings
- Minimum values
- Empty strings vs null
Performance tests:
- Response time under load
- Concurrent requests
Q: How do you handle API dependencies in testing?
Answer:
Strategies:
1. Mocking:
# Mock external payment API
@responses.activate
def test_process_payment():
responses.add(
responses.POST,
"https://payment.api/charge",
json={"status": "success"},
status=200
)
# Test your API that calls payment API2. Contract testing:
- Define expected behavior in contract
- Both consumer and provider verify against contract
- Catch integration issues without full integration
3. Test doubles:
- Stubs: Return canned responses
- Mocks: Verify interactions
- Fakes: Simplified implementations
4. Test environments:
- Dedicated test instance of dependency
- Sandbox/staging versions
- Service virtualization
Q: What is contract testing?
Answer:
Contract testing verifies that services agree on their API contract:
Consumer Provider
| |
|-- Defines expectations ---|
| (contract) |
| |
| Verifies contract ---|
| |How it works (Pact example):
Consumer side:
// Define what consumer expects
pact.given("user exists")
.uponReceiving("a request for user")
.path("/users/1")
.method("GET")
.willRespondWith()
.status(200)
.body(new PactDslJsonBody()
.integerType("id")
.stringType("name"));Provider side:
// Verify provider meets expectations
@Provider("UserService")
@PactBroker
public class UserProviderTest {
@TestTemplate
void pactVerification(PactVerificationContext context) {
context.verifyInteraction();
}
}Benefits:
- Fast feedback (no full integration)
- Clear ownership (who broke the contract?)
- Independent deployability
Postman Questions
Q: How do you organize tests in Postman?
Answer:
Hierarchy:
Workspace
└── Collection (API or feature)
└── Folder (endpoint group)
└── Request
└── TestsBest practices:
- One collection per API or feature
- Folders for logical grouping (Auth, Users, Orders)
- Descriptive request names
- Environment variables for different stages
Q: How do you write tests in Postman?
Answer:
// Status code
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
// Response time
pm.test("Response time is less than 500ms", function () {
pm.expect(pm.response.responseTime).to.be.below(500);
});
// JSON body
pm.test("Response has correct structure", function () {
const response = pm.response.json();
pm.expect(response).to.have.property("id");
pm.expect(response.name).to.be.a("string");
pm.expect(response.email).to.include("@");
});
// Headers
pm.test("Content-Type is JSON", function () {
pm.response.to.have.header("Content-Type", /application\/json/);
});
// Array validation
pm.test("Returns array of users", function () {
const response = pm.response.json();
pm.expect(response).to.be.an("array");
pm.expect(response.length).to.be.above(0);
response.forEach(user => {
pm.expect(user).to.have.all.keys("id", "name", "email");
});
});Q: How do you use variables in Postman?
Answer:
Variable scopes (precedence order):
- Local (temporary, current request)
- Data (from data file during collection run)
- Environment (stage-specific)
- Collection (shared within collection)
- Global (shared across workspace)
Setting variables:
// Pre-request script
pm.environment.set("userId", "123");
pm.collectionVariables.set("baseUrl", "https://api.example.com");
// From response (Tests tab)
const response = pm.response.json();
pm.environment.set("authToken", response.token);Using variables:
URL: {{baseUrl}}/users/{{userId}}
Header: Authorization: Bearer {{authToken}}
Body: { "name": "{{userName}}" }Q: How do you chain requests in Postman?
Answer:
Use Pre-request scripts and Tests to pass data:
Request 1 (Login):
// Tests tab
const response = pm.response.json();
pm.environment.set("authToken", response.token);
pm.environment.set("userId", response.user.id);Request 2 (Get User):
GET {{baseUrl}}/users/{{userId}}
Authorization: Bearer {{authToken}}Dynamic workflow:
// Tests tab - conditional next request
if (pm.response.json().status === "pending") {
postman.setNextRequest("Check Status");
} else {
postman.setNextRequest("Process Complete");
}REST Assured Questions
Q: How do you write a basic REST Assured test?
Answer:
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
@Test
public void testGetUser() {
given()
.baseUri("https://api.example.com")
.header("Authorization", "Bearer " + token)
.pathParam("id", 123)
.when()
.get("/users/{id}")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("id", equalTo(123))
.body("name", notNullValue())
.body("email", containsString("@"));
}
@Test
public void testCreateUser() {
User user = new User("John", "john@example.com");
given()
.contentType(ContentType.JSON)
.body(user)
.when()
.post("/users")
.then()
.statusCode(201)
.body("id", notNullValue())
.body("name", equalTo("John"));
}Q: How do you extract values from responses in REST Assured?
Answer:
// Extract single value
int userId = given()
.when()
.get("/users/1")
.then()
.extract()
.path("id");
// Extract as object
User user = given()
.when()
.get("/users/1")
.then()
.extract()
.as(User.class);
// Extract response for multiple values
Response response = given()
.when()
.get("/users")
.then()
.extract()
.response();
List<String> names = response.path("name");
String firstEmail = response.path("[0].email");
// Use JsonPath
JsonPath json = response.jsonPath();
int count = json.getInt("total");
List<User> users = json.getList("data", User.class);Q: How do you validate JSON Schema in REST Assured?
Answer:
import static io.restassured.module.jsv.JsonSchemaValidator.*;
@Test
public void testResponseMatchesSchema() {
given()
.when()
.get("/users/1")
.then()
.statusCode(200)
.body(matchesJsonSchemaInClasspath("schemas/user-schema.json"));
}Schema file (user-schema.json):
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": ["id", "name", "email"],
"properties": {
"id": { "type": "integer" },
"name": { "type": "string" },
"email": { "type": "string", "format": "email" },
"createdAt": { "type": "string", "format": "date-time" }
}
}Advanced Scenarios
Q: How do you test APIs with pagination?
Answer:
@Test
public void testPagination() {
// First page
Response page1 = given()
.queryParam("page", 1)
.queryParam("limit", 10)
.when()
.get("/users")
.then()
.statusCode(200)
.body("data.size()", equalTo(10))
.body("pagination.currentPage", equalTo(1))
.body("pagination.hasNext", equalTo(true))
.extract().response();
// Verify total and calculate pages
int total = page1.path("pagination.total");
int totalPages = (int) Math.ceil(total / 10.0);
// Last page
given()
.queryParam("page", totalPages)
.queryParam("limit", 10)
.when()
.get("/users")
.then()
.body("pagination.hasNext", equalTo(false));
}Q: How do you test file upload via API?
Answer:
@Test
public void testFileUpload() {
File file = new File("test-file.pdf");
given()
.multiPart("file", file, "application/pdf")
.multiPart("description", "Test document")
.when()
.post("/documents/upload")
.then()
.statusCode(201)
.body("filename", equalTo("test-file.pdf"))
.body("size", greaterThan(0));
}Postman:
- Set body type to
form-data - Add file field with type
File - Select file to upload
Q: How do you test rate limiting?
Answer:
@Test
public void testRateLimiting() {
int limit = 100;
// Make requests up to limit
for (int i = 0; i < limit; i++) {
given()
.when()
.get("/api/resource")
.then()
.statusCode(200);
}
// Next request should be rate limited
given()
.when()
.get("/api/resource")
.then()
.statusCode(429)
.header("Retry-After", notNullValue());
}Best Practices
Q: What are API testing best practices?
Answer:
Test design:
- Test positive and negative scenarios
- Validate response structure, not just status
- Use schema validation
- Test boundary conditions
- Include security tests
Maintainability:
- Use data-driven testing
- Externalize test data
- Create reusable helper methods
- Follow consistent naming conventions
Reliability:
- Don't depend on external services (mock when possible)
- Create test data, don't rely on existing
- Clean up after tests
- Handle async operations properly
Performance:
- Keep tests fast
- Run in parallel when possible
- Mock expensive operations
- Monitor test suite performance
CI/CD integration:
- Run tests automatically
- Fail builds on test failures
- Generate reports
- Track trends over time
Quiz on API Testing Interview
Your Score: 0/10
Question: Which HTTP method should be used to partially update a resource?
Continue Reading
Frequently Asked Questions (FAQs) / People Also Ask (PAA)
Should I learn Postman or code-based API testing first?
How do I test APIs when documentation is incomplete?
What's the difference between Postman and REST Assured?
How do I handle APIs that require complex authentication flows?
Should I test both API and UI for the same feature?
How do I test APIs with async operations?
What should I know about GraphQL testing?
How important is JSON Schema validation in interviews?