API Testing Interview Guide (50+ Questions)
Prepared for: Bansal, Vitul — Quality Consultant
A comprehensive, practical guide with detailed answers, real-world scenarios, and sample Postman &
RestAssured scripts. Use this as a single reference for interviews and on-the-job API quality work.
Contents: Fundamentals · HTTP/REST · Validation & Assertions · Auth & Security · Automation & Frameworks · Performance &
Reliability · Advanced/Microservices · Real-world Scenarios · Cheat Sheets
1. Fundamentals
Q1. What is API testing and why is it critical?
API testing validates endpoints, request/response contracts, status codes, data integrity, and non-functional
aspects (performance, security). It decouples validation from the UI, enabling fast, reliable checks of the
system-of-record and inter-service communication.
Q2. Key differences between UI, Unit, Integration, and API testing
UI tests exercise user flows via the interface; unit tests target isolated functions; integration tests verify module
interaction; API tests validate service contracts, behaviors, and interoperability at the HTTP/message layer
without a UI.
Q3. Common API styles: REST, SOAP, GraphQL, gRPC
REST uses resource-centric HTTP semantics, SOAP is XML-based with strict messaging and WS-*
standards, GraphQL offers client-driven queries over a single endpoint, and gRPC uses HTTP/2 with Protocol
Buffers for streaming and efficiency.
Q4. Key HTTP elements relevant to testing
Methods (GET/POST/PUT/PATCH/DELETE), status codes (2xx/3xx/4xx/5xx), headers (Auth, Content-Type,
Caching), body formats (JSON/XML), and idempotency/safety semantics.
Q5. What is a contract in API testing?
A contract defines the API’s request/response schema, headers, status codes, and rules (e.g., pagination),
typically captured via OpenAPI/Swagger or WSDL. Tests assert conformance to this contract across versions.
Q6. Test data strategies for APIs
Use synthetic data with known edge cases, seeded fixtures, environment-specific test accounts, and isolation
via tenants. Reset or tear down to ensure independence and repeatability.
Q7. Versioning and backward compatibility
Prefer additive changes; version via URI (/v1), header, or content negotiation. Maintain contract compatibility
and deprecation windows; test with mixed client versions.
Q8. Idempotency and safety
GET/HEAD are safe and idempotent; PUT and DELETE should be idempotent; POST is typically
non-idempotent unless backed by idempotency keys. Tests must assert repeated calls yield consistent
outcomes.
Q9. Pagination and filtering
Validate default limits, max limits, cursor/offset behaviors, determinism across pages, and edge conditions
(empty page, last page).
Q10. Error handling and problem details
Ensure standardized errors (code, message, detail, traceId), consistent status codes, and actionable
diagnostics (RFC 7807 style).
2. HTTP & REST
Q11. Difference between PUT and PATCH
PUT replaces the full resource and is idempotent; PATCH applies partial updates to specific fields; tests must
verify unchanged fields remain intact and conflict detection is enforced.
Q12. Cache control and ETags
Validate Cache-Control headers, ETag generation, conditional requests (If-None-Match/If-Match), and
304/412 behaviors to prevent stale data and concurrency issues.
Q13. Content negotiation
Test Accept and Content-Type headers; ensure proper 415 (unsupported media type) and 406 (not
acceptable) responses when misused.
Q14. Rate limiting
Assert presence of limit headers (X-RateLimit-Limit/Remaining/Reset) and correct 429 behavior with
retry-after; simulate burst traffic to validate policies.
Q15. Retry semantics and idempotency keys
For POSTs, validate support for idempotency keys to avoid duplicates; assert server deduplication and stable
responses across retries.
Q16. HATEOAS and discoverability
If applicable, verify hypermedia links, allowed transitions, and that navigation aligns with authorization scopes.
Q17. HTTP status code validation
Map business outcomes to correct codes (201 for create, 202 for async, 204 for no content, 400/422 for bad
request/validation, 404, 409, 500/503).
Q18. Security headers
Check Strict-Transport-Security, X-Content-Type-Options, Content-Security-Policy (for APIs behind
gateways), and that only HTTPS is supported.
Q19. Cross-origin resource sharing (CORS)
Validate preflight responses, allowed origins/methods/headers, and that credentials are handled securely (no
wildcard with credentials).
Q20. OpenAPI/Swagger usage in testing
Leverage schema to auto-generate tests, assert fields/types, and detect breaking changes via diffing across
versions.
3. Validation & Assertions
Q21. How to validate response structure
Assert status, headers, and JSON structure including required fields, types, formats (UUID, email), ranges,
and nullability.
Q22. JSON schema validation with RestAssured
Use JsonSchemaValidator to match response body to a schema file; include required properties and
constraints.
RestAssured: JSON Schema Validation
import static [Link].*;
import static [Link];
@Test
public void shouldMatchSchema() {
given()
.baseUri("[Link]
.when()
.get("/orders/123")
.then()
.statusCode(200)
.body(matchesJsonSchemaInClasspath("schemas/[Link]"));
}
Q23. Postman tests: status, headers, and body
Use [Link]/[Link] to assert response code, content-type, and body fields.
Postman: Basic Assertions
[Link]('Status is 200', function () {
[Link](200);
});
[Link]('Content-Type is JSON', function () {
[Link]('Content-Type');
[Link]([Link]('Content-Type')).[Link]('application/json');
});
[Link]('Body fields', function () {
const json = [Link]();
[Link](json).[Link]('id');
[Link]([Link]).[Link].a('number');
});
Q24. Validating arrays, ordering, and uniqueness
Check array lengths, sort order, uniqueness of IDs, and stable pagination across repeated calls.
Q25. Date/time and timezone handling
Assert ISO-8601 formats, UTC normalization, and correct conversions for user locale; detect DST edge cases.
Q26. Floating-point and precision
Avoid equality on floats; use tolerances; validate currency fields as decimal strings to prevent rounding issues.
Q27. Error payload assertions
Check standardized fields: code, message, details, path, timestamp, traceId; ensure no sensitive leakage
(stack traces).
Q28. Contract testing in CI
Integrate schema validation and example-based tests in CI/CD; fail builds on breaking changes; publish
artifacts for consumers.
Q29. Negative testing techniques
Send malformed JSON, invalid enums, oversized payloads, missing required fields, and unauthorized
requests to validate robustness and error mapping.
4. Authentication & Security
Q30. Common auth mechanisms (API keys, Basic, OAuth2, JWT)
Test token issuance, expiry, refresh, scope enforcement, and revocation. Ensure TLS everywhere and secrets
never logged or echoed.
Q31. OAuth 2.0 flows and testing
Validate authorization code, client credentials, and refresh token flows; assert scopes, audience, and PKCE
where applicable.
Q32. JWT validation
Check signature, issuer (iss), audience (aud), expiry (exp), and subject (sub). Reject expired or tampered
tokens and enforce clock skew.
Q33. Role-based access control (RBAC)
Create tests for least privilege, forbidden resource access (403), and data partitioning (tenant isolation).
Q34. Secrets management
Use environment variables and secure vaults; never hardcode secrets in scripts; rotate keys and audit usage.
Q35. Input validation and injection
Assert strict validation of query/body parameters to prevent SQL/NoSQL/command injection; sanitize and
encode outputs.
Q36. TLS and certificate pinning
Verify only HTTPS accepted, correct TLS versions/ciphers, and certificate validity; mobile clients may use cert
pinning—test fallback behavior.
Q37. Security testing with Postman
Automate tests for expired tokens, replay attacks (idempotency keys), and attempt path traversal or insecure
direct object references (IDOR).
Postman: Auth Header Example
// Set Bearer token from environment
[Link]({ key: 'Authorization', value: `Bearer ${[Link]('token')
[Link]('Unauthorized without token', function () {
[Link]({
url: [Link](),
method: [Link],
header: []
}, function (err, res) {
[Link]([Link]).[Link]([401, 403]);
});
});
5. Automation & Frameworks
Q38. When to choose Postman vs RestAssured vs Karate
Postman is great for exploratory and quick automation via Newman; RestAssured integrates naturally with
Java test stacks; Karate provides BDD-style DSL and good HTTP assertions with minimal code.
Q39. Newman for CI
Export collections and run via Newman in CI; parameterize environments (staging/prod), generate HTML/JUnit
reports, and gate deployments on pass rates.
Q40. RestAssured basics
Use given/when/then syntax, request specs, and reusable auth; combine with JUnit/TestNG, Allure reports,
and data-driven tests.
RestAssured: Basic Test
import static [Link].*;
import [Link];
import [Link];
RequestSpecification spec = new RequestSpecBuilder()
.setBaseUri("[Link]
.addHeader("Authorization", "Bearer " + [Link]("TOKEN"))
.build();
@Test
public void listOrders() {
given().spec(spec)
.when().get("/orders")
.then().statusCode(200)
.extract().body().jsonPath().getList("[Link]");
}
Q41. Data-driven tests
Drive tests from CSV/JSON; in Postman use iteration data with Newman; in RestAssured load fixtures and
parameterize using @Parameterized tests.
Q42. Mocking and stubbing
Use WireMock, Postman Mock Servers, or test doubles to simulate dependencies; validate consumer
behavior under edge responses (timeouts, 5xx, malformed).
Q43. Contract testing with Pact
Define consumer expectations and provider verification; integrate with CI to prevent breaking changes across
microservices.
Q44. Environment management
Separate config for base URLs, secrets, and timeouts per environment; centralize in CI and avoid
environment-specific logic in tests.
Q45. Reporting and metrics
Publish JUnit/Allure reports, track flakiness, mean response times, and error distributions; make test results
actionable for teams.
6. Performance & Reliability
Q46. Load testing APIs
Use JMeter, Gatling, or k6 to simulate realistic traffic, ramps, and spikes; analyze throughput, latency
percentiles (p95/p99), and saturation.
Q47. Soak testing
Run extended tests to detect memory leaks, resource exhaustion, and token expiry/rotation issues over time.
Q48. Chaos and resilience
Introduce faults (latency, aborts) and assert timeouts, retries, and circuit breaking; ensure graceful
degradation.
Q49. Caching correctness
Validate cache hits/misses, invalidation policies, and stale-while-revalidate behaviors; ensure consistency
across nodes.
Q50. Async processing and 202 Accepted
For long-running operations, assert 202 responses with status endpoints or webhooks; validate eventual
consistency and idempotent retries.
Q51. Rate limit/backoff
Measure how clients respond to 429, implement exponential backoff, and verify server-side fairness and
quotas.
7. Advanced & Microservices
Q52. Distributed tracing and correlation IDs
Propagate traceId/correlationId across services and assert presence in logs; include in error payloads for
diagnostics.
Q53. Service discovery and gateways
Test gateway policies (auth, throttling), path rewrites, and header propagation; verify zero trust boundaries and
mTLS where applicable.
Q54. Event-driven APIs
For webhook/Kafka integrations, validate signatures, retries, deduplication, and consumer idempotency.
Q55. Serialization formats
Test JSON vs Protobuf/Avro, backward compatibility, and evolution of schemas; ensure unknown fields are
ignored appropriately.
Q56. Multi-tenant isolation
Assert tenant scoping in queries and data segregation; test cross-tenant access attempts return 403/404
securely.
Q57. Blue/green and canary releases
Verify compatibility and routing during gradual rollouts; test mixed-version interactions and rollback paths.
8. Real-world Scenarios & Sample Scripts
Q58. Scenario: Creating an order and verifying downstream effects
Create an order (201), retrieve it (GET), verify inventory decrement and event emission; retry POST with
idempotency key and assert no duplicates.
Postman: Create Order + Idempotency
const idKey = [Link]('{{$randomUUID}}');
[Link]('idemKey', idKey);
[Link]({ key: 'Idempotency-Key', value: idKey });
[Link]('Created (201) and returns resource location', function () {
[Link](201);
[Link]([Link]('Location')).[Link](/\/orders\/[0-9a-f-]+/);
});
RestAssured: Verify Inventory Side-Effect
String orderId =
given().baseUri("[Link]
.body("{\"sku\":\"ABC-123\",\"qty\":1}")
.post("/orders")
.then().statusCode(201)
.extract().header("Location").replaceAll(".*/", "");
// Downstream inventory check
given().baseUri("[Link]
.when().get("/inventory/ABC-123")
.then().statusCode(200)
.body("available", [Link](100));
Q59. Scenario: Pagination correctness
Request pages with size=50; assert no overlaps, stable ordering by createdAt, and last page shorter or empty
when exceeding results.
Postman: Pagination Assertions
function ids(list){return [Link](i => [Link])}
const j1 = [Link]();
[Link]('Page size <= 50', function () {
[Link]([Link]).[Link](50);
});
// Next page
[Link]([Link]({page: Number([Link]('page')) + 1}).
const j2 = [Link]();
[Link]('No overlaps across pages', function () {
[Link](ids([Link]).filter(id => ids([Link]).includes(id))).[Link](0);
});
});
Q60. Scenario: Concurrency with ETags
Obtain ETag on GET, update with If-Match header; expect 200 on first update and 412 Precondition Failed on
stale ETag.
Postman: ETag Concurrency
const etag = [Link]('ETag');
[Link]('etag', etag);
// Attempt update
[Link]({
url: [Link]('baseUrl') + '/profiles/123',
method: 'PUT',
header: [{ key: 'If-Match', value: etag }, { key: 'Content-Type', value: 'application/jso
body: { mode: 'raw', raw: [Link]({ name: 'Vitul' }) }
}, function (err, res) {
[Link]('Update accepted', function () { [Link]([Link]).[Link]([200,204]); });
});
Q61. Scenario: OAuth2 client credentials
Obtain token, call resource with Bearer token, and assert 401/403 when token expires or scope missing.
Postman: Token Retrieval
[Link]({
url: [Link]('authUrl'),
method: 'POST',
header: [{ key: 'Content-Type', value: 'application/x-www-form-urlencoded' }],
body: { mode: 'urlencoded', urlencoded: [
{ key: 'grant_type', value: 'client_credentials' },
{ key: 'client_id', value: [Link]('clientId') },
{ key: 'client_secret', value: [Link]('clientSecret') },
{ key: 'scope', value: 'orders:read' }
]}
}, function (err, res) {
[Link]('token', [Link]().access_token);
});
Q62. Scenario: Validating error payloads
Trigger 422 by sending invalid field; assert error code, message, field path, and correlationId is present for
support.
Q63. Scenario: Webhook signature verification
Simulate webhook with HMAC signature header; assert server verifies signature, returns 2xx once, and
deduplicates events.
Q64. Scenario: Async job polling
Submit job (202 Accepted) and poll status until completed; assert final resource exists and intermediate states
are valid.
RestAssured: Polling
String jobId = given().baseUri("[Link]
.post("/jobs")
.then().statusCode(202)
.extract().path("id");
await().atMost([Link](30)).untilAsserted(() -> {
given().baseUri("[Link]
.get("/jobs/" + jobId)
.then().statusCode(200)
.body("status", [Link]("QUEUED","RUNNING","SUCCEEDED","FAILE
});
9. Cheat Sheets & Quick Reference
HTTP Status Codes (most common)
2xx: Success (200 OK, 201 Created, 202 Accepted, 204 No Content)
3xx: Redirection (301 Moved Permanently, 304 Not Modified)
4xx: Client errors (400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 409 Co
5xx: Server errors (500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable)
Common Headers
Authorization: Bearer <token>
Content-Type: application/json
Accept: application/json
Idempotency-Key: <uuid>
If-Match: <etag>
Cache-Control: no-cache
X-Request-Id: <traceId>
Postman Testing Snippets
[Link]('Response time < 500ms', function(){
[Link]([Link]).[Link](500);
});
[Link]('JSON has required fields', function(){
const j = [Link]();
['id','createdAt','status'].forEach(k => [Link](j).[Link](k));
});
RestAssured Quick Setup
[Link] = "[Link]
[Link]();
Response res = given()
.header("Authorization", "Bearer " + [Link]("TOKEN"))
.get("/health");
assertEquals(200, [Link]());
Tips for Interviews
Anchor your answers to concrete examples (pagination, idempotency, ETags). Mention tooling choices and CI
integration. Emphasize security awareness (auth, headers) and non-functional testing (latency percentiles,
reliability).
Appendix: Useful Links & Standards (for further reading)
RFC 7231 (HTTP/1.1 Semantics), RFC 7807 (Problem Details), OAuth 2.0 (RFC 6749), JSON Web Tokens
(RFC 7519)
OpenAPI Specification, OWASP API Security Top 10, Postman Docs, RestAssured Docs