QA Interview
Top 30 API testing Interview Questions and Answers (2026)
Study the top API testing interview questions for 2026 with 30 model answers on HTTP, automation, contracts, security, reliability, debugging, and test design.
31 min read | 3,682 words
TL;DR
The top API testing interview questions cover HTTP semantics, test design, automation structure, contracts, authentication and authorization, reliability, performance, and debugging. Answer with business invariants and observable evidence, then explain the tradeoffs and failure modes behind your approach.
Key Takeaways
- API testing validates behavior, contracts, security, reliability, and state changes, not only status codes.
- Strong answers connect HTTP method semantics, representation, caching, idempotency, and error handling to business invariants.
- A maintainable suite separates transport helpers, domain actions, test data, oracles, and diagnostics without hiding requests.
- Contracts catch compatibility problems, while integration and end-to-end tests cover runtime wiring and critical journeys.
- Security coverage includes authentication, authorization, input handling, data exposure, abuse controls, and auditability.
- Reliability tests model timeouts, retries, duplicates, reordering, partial failure, concurrency, and recovery.
- The best debugging method traces one request across client, gateway, service, dependencies, data, and observability.
The top API testing interview questions assess whether you can validate a service contract, its business effects, and its behavior under failure. A strong API tester reasons about HTTP, data, authorization, idempotency, dependencies, compatibility, performance, security, and diagnostics instead of checking only status codes.
This 2026 guide provides 30 model answers and a runnable Node.js API test. It stays tool-neutral where the engineering principle matters, so you can apply the approach in REST Assured, Playwright, Supertest, pytest, Karate, Postman, or another supported stack.
Learn the contract first. Tool syntax is useful, but an interview answer becomes credible when it states the invariant, request, observable evidence, failure model, and tradeoff.
TL;DR
| Area | Minimum evidence | High-value follow-up |
|---|---|---|
| HTTP | Method, status, headers, and representation | Caching and conditional requests |
| Business behavior | Response plus durable state and side effects | Concurrency and recovery |
| Security | Authentication and object authorization | Abuse, exposure, and audit |
| Reliability | Timeout, retry, idempotency, and dependency failure | Duplicates and ambiguous outcomes |
| Contracts | Schema and semantic compatibility | Consumer-driven verification |
| Automation | Isolated data, clear helpers, and diagnostics | Parallelism and ownership |
| Performance | Workload, percentiles, errors, and saturation | Capacity and bottleneck diagnosis |
For any API scenario, ask six questions: Who is the consumer? What invariant must hold? What state changes? Which trust boundary is crossed? How can the operation fail? What evidence proves the outcome?
1. Top API testing interview questions: Build a Complete Answer Map
Organize preparation into transport, domain, trust, failure, and operation. Transport includes method, URL, headers, media type, status, and body. Domain includes validation, state transitions, side effects, and invariants. Trust includes identity, permission, tenant isolation, and sensitive data. Failure includes timeouts, retries, duplicates, concurrency, and dependencies. Operation includes logs, traces, metrics, rollout, and recovery.
This map prevents status-code tunnel vision. A create-order request can return 201 Created while storing the wrong total, exposing another tenant's data, publishing duplicate events, or omitting an audit record. The response is one observation, not the entire oracle.
Clarify the API style. REST, GraphQL, gRPC, asynchronous messaging, and webhooks have different contracts. Even within REST, a team can use custom actions, eventual processing, or versioned media. Do not force every system into a textbook resource model. State the documented contract and evaluate it consistently.
Interviewers often change one constraint. They may add a slow dependency, concurrent clients, multiple regions, an old consumer, or a strict latency objective. Evolve your strategy by identifying which assumption broke. Do not discard the original plan or respond with an unrelated tool.
Prepare one deep example involving a mutation and one involving retrieval. The mutation should cover idempotency, state, events, and recovery. Retrieval should cover authorization, filtering, pagination, caching, and data exposure.
2. Explain HTTP Semantics Precisely
GET retrieves a representation and is defined as safe and idempotent by HTTP semantics, although poorly designed servers can violate that expectation. HEAD is like GET without response content. POST submits data for resource-specific processing and is not inherently idempotent. PUT creates or replaces the state of a target resource and is idempotent. PATCH applies a partial modification and may or may not be idempotent depending on the patch operation. DELETE is idempotent in intended effect even if repeated responses differ.
Status codes express protocol outcomes. 200 is a general success, 201 indicates resource creation, 202 indicates accepted processing not yet complete, and 204 has no response content. 400 covers a malformed or invalid request in many contracts, 401 indicates missing or invalid authentication, 403 indicates understood identity without permission, 404 means the target is not found or is intentionally concealed, 409 represents a state conflict, 412 a failed precondition, 422 semantically invalid content where used, and 429 rate limiting. 500 class codes indicate server-side failure.
Do not prescribe one code without reading the API contract. Test consistency, client usefulness, and absence of sensitive internal detail. A structured error can include a stable code, safe message, field details, and correlation identifier.
Headers are part of behavior. Validate Content-Type, Accept, authentication, caching, conditional request headers, location after creation, retry guidance, correlation IDs, and deprecation or version information when documented. Test missing, duplicate, malformed, and unsupported header values.
3. Design Positive, Negative, Boundary, and Stateful Scenarios
Begin with equivalence classes and boundaries for every input. For an amount, cover valid range edges, zero, negative, excessive value, wrong type, missing value, precision, and currency compatibility. For strings, consider empty, whitespace, maximum length, Unicode, normalization, control characters, and prohibited content according to the contract.
Negative testing is not random invalid data. Each case should target a rule or failure mechanism and have an oracle. Distinguish malformed JSON, structurally valid but semantically invalid input, unsupported media type, missing identity, insufficient scope, nonexistent resource, invalid state transition, dependency failure, and concurrency conflict.
Stateful APIs need transition coverage. If an order can move from draft to confirmed to shipped, test legal transitions, repeated transitions, skipped transitions, stale updates, concurrent updates, cancellation boundaries, and terminal states. Verify version or precondition behavior if clients can overwrite one another.
For creation, inspect durable state and side effects such as events, messages, inventory, audit, or email. For deletion, test authorization, references, soft versus hard deletion, repeated deletion, restoration, and data retention. For search, test filtering, sorting, pagination, stable ordering, empty results, permissions, and special characters.
The API error handling and negative testing guide provides a broader failure matrix. Keep test data minimal and isolated so a failing assertion identifies the violated rule instead of an unrelated fixture dependency.
4. Test Authentication, Authorization, and API Security
Authentication establishes identity. Authorization decides what that identity may do with a resource or function. Test them separately. A valid token for user A must not allow access to user B's order by changing an identifier. An ordinary user must not gain an administrative action by calling its endpoint directly.
Cover missing, malformed, expired, not-yet-valid, revoked, wrong-audience, wrong-issuer, and insufficient-scope tokens according to the system. Avoid assuming the token format. Opaque tokens and signed tokens have different client visibility, while the authorization outcome remains testable.
Check object-level and function-level permission across read, create, update, delete, export, bulk, and nested resources. Include tenant isolation and indirect identifiers. A 404 used to conceal existence can be correct, but logs and audit should still support authorized investigation.
Security testing also covers input injection, excessive data exposure, mass assignment, unsafe file or URL handling, rate abuse, resource exhaustion, insecure dependency consumption, weak configuration, inventory gaps, and poor logging. Test only in authorized environments with bounded traffic and approved data.
Secrets belong in runtime secret management, not source, fixtures, screenshots, or reports. Redact authorization headers and sensitive fields while retaining safe request identifiers. The API security testing with OWASP guide can help turn common risks into test charters.
5. Build a Maintainable API Automation Architecture
Tests should express domain intent while leaving enough transport detail for diagnosis. Separate low-level HTTP configuration, typed or validated domain clients, data builders, scenario fixtures, assertions, and reporting. Avoid one generic helper that accepts any method, URL, and map, because it moves endpoint knowledge into every test while hiding useful contracts.
| Component | Responsibility | Design caution |
|---|---|---|
| HTTP client | Base URL, TLS, timeout, safe logging | Global mutable headers |
| Domain client | Endpoint request and response contract | Hiding every status assertion |
| Data builder | Minimal valid and boundary payloads | Huge shared fixtures |
| Fixture | Create and dispose test resources | Cleanup that masks the test failure |
| Oracle | Schema, domain state, and side effects | Snapshot-only assertions |
| Reporter | Correlation, request, response, and timing | Leaking tokens or personal data |
Configuration must be explicit and validated. Separate environments through runtime values, but do not scatter environment conditionals through assertions. If environments intentionally differ, model the capability and test the correct contract rather than skipping silently.
Parallel tests require unique resources and deterministic cleanup. Use generated identifiers, per-worker namespaces, or supported tenant isolation. Cleanup should be idempotent and should not delete shared reference data. When cleanup fails, report it separately without replacing the original assertion failure.
Schema validation catches missing, wrong-type, or unexpected structural data according to policy. Domain assertions still need to confirm values and relationships. A response can match JSON Schema while violating the order total. Use REST Assured JSON Schema validation if your interview stack is Java.
6. Run a Complete API Test With Node.js
This single file creates an API handler with the standard Web Request and Response classes, then verifies validation plus idempotent replay. It uses current Node.js built-ins, opens no network port, and needs no third-party service. Save it as orders-api.test.mjs and run node --test orders-api.test.mjs.
import assert from 'node:assert/strict';
import test from 'node:test';
function createOrdersHandler() {
const operations = new Map();
return async function handle(request) {
const url = new URL(request.url);
if (request.method !== 'POST' || url.pathname !== '/orders') {
return new Response(null, { status: 404 });
}
const body = await request.json();
const key = request.headers.get('idempotency-key');
if (!key || !Number.isSafeInteger(body.totalCents) || body.totalCents <= 0) {
return new Response(JSON.stringify({ code: 'invalid_order' }), {
status: 400,
headers: { 'content-type': 'application/json' }
});
}
const stored = operations.get(key);
const order = stored ?? { id: `ord_${operations.size + 1}`, ...body };
operations.set(key, order);
return new Response(JSON.stringify(order), {
status: 201,
headers: { 'content-type': 'application/json' }
});
};
}
test('validates input and replays one logical order', async () => {
const handle = createOrdersHandler();
const makeRequest = (key, totalCents) =>
new Request('https://api.example.test/orders', {
method: 'POST',
headers: {
'content-type': 'application/json',
'idempotency-key': key
},
body: JSON.stringify({ totalCents, currency: 'USD' })
});
const first = await handle(makeRequest('checkout-781', 4200));
const retry = await handle(makeRequest('checkout-781', 4200));
assert.equal(first.status, 201);
assert.deepEqual(await retry.json(), await first.json());
const invalid = await handle(makeRequest('checkout-782', 0));
assert.equal(invalid.status, 400);
assert.equal((await invalid.json()).code, 'invalid_order');
});
The example is deliberately small. A production service must handle malformed JSON safely, bind an idempotency key to request content and account scope, coordinate concurrency atomically, persist outcomes, define retention, and distinguish first creation from replay according to its contract. Calling out these missing properties is a useful interview follow-up.
7. Cover Contracts, Asynchrony, Reliability, and Performance
Schema tests validate shape. Consumer-driven contract tests capture interactions a consumer relies on and verify them against a provider. They provide earlier compatibility feedback than broad end-to-end tests, but they do not prove runtime networking, identity, deployment configuration, data migration, or a complete user journey. See the Pact contract testing guide for a practical model.
Asynchronous APIs can return 202 Accepted with a status resource or publish events. Test acceptance separately from completion. Cover delayed, duplicate, missing, and reordered messages, consumer retry, dead-letter handling, replay, and reconciliation. Correlation and operation identity must survive the workflow.
Reliability testing models ambiguous outcomes. A client can time out after the server commits work. Safe retry requires idempotency, and automatic retries need bounded attempts, appropriate methods, backoff, jitter, and respect for server guidance. Test dependency timeouts, circuit or fallback behavior, partial failure, and recovery without generating uncontrolled load.
Performance testing begins with an objective: response-time regression, capacity, endurance, scalability, or resilience. Define representative operations, data, arrival pattern, concurrency, warm-up, duration, environment, and success criteria. Report latency percentiles with throughput, errors, and resource saturation. An average alone hides tail behavior.
Rate-limit tests verify scope, boundaries, response contract, recovery, fairness, and distributed enforcement in an approved environment. Do not run an accidental denial-of-service test. Coordinate capacity work, protect data, and include a stop condition.
8. Answer Top API testing interview questions With Evidence
Use a compact pattern for any scenario: contract, risks, cases, oracles, and operations. Define who calls the API and what success means. Rank failures by user and business impact. Select cases that distinguish mechanisms. State which evidence proves each outcome. Finish with diagnostics, ownership, and residual risk.
For a pagination question, do not only test page=1. Clarify offset, cursor, or keyset behavior. Test empty, first, middle, and final pages, boundary size, invalid cursor, stable ordering, inserts and deletes between requests, authorization filtering, duplicates, omissions, and metadata. The API pagination testing guide provides deeper examples.
For a debugging question, follow one request identity. Compare client serialization, gateway routing, auth decision, service validation, downstream calls, database state, event publication, and response mapping. Use logs, traces, metrics, and safe replay. Separate the first symptom from the root cause.
For a tool question, explain capability and design before syntax. REST Assured integrates naturally with Java test ecosystems. Playwright request contexts can share test-runner fixtures with browser flows. Supertest works well around Node HTTP apps. pytest supports Python clients and fixtures. Karate offers a domain-specific API testing style. Choose based on team language, product, diagnostics, and maintainability.
Interview Questions and Answers
Q1: What is API testing?
API testing validates an interface's protocol contract, business behavior, security, reliability, and operational evidence. It sends requests or messages directly and checks responses, durable state, side effects, and failure behavior. The goal is trustworthy consumer outcomes, not merely successful HTTP calls.
Q2: What is the difference between API testing and UI testing?
API testing exercises service interfaces directly, so it is usually faster and more controllable for rules, data, and failures. UI testing validates presentation, browser behavior, accessibility, and complete user journeys. A layered strategy uses both according to the risk rather than replacing one with the other.
Q3: What should you validate in an API response?
I validate status, headers, media type, schema, field values, relationships, ordering, and the documented error model. For mutations, I also verify durable state and emitted effects. I check that sensitive data is absent and diagnostics such as correlation IDs are useful.
Q4: Explain GET, POST, PUT, PATCH, and DELETE.
GET retrieves, POST submits for resource-specific processing, PUT creates or replaces a target representation, PATCH partially modifies, and DELETE removes the target effect. GET, PUT, and DELETE have idempotent semantics, while POST and some patch operations need application-specific protection. I still test the documented behavior because implementations can violate intended semantics.
Q5: What is idempotency?
Idempotency means repeating one logical operation does not create an unintended additional effect. For a mutation, a client can provide an operation key that the server binds to account, input, and result according to its contract. I test identical retry, concurrent retry, changed input, ambiguous failure, retention, and durable state.
Q6: What is the difference between 401 and 403?
401 Unauthorized indicates that valid authentication credentials are missing or not accepted, despite the historical name. 403 Forbidden means the server understands the identity but refuses the requested action. Some APIs return 404 to conceal resource existence, so I follow the security contract consistently.
Q7: How do you test authentication?
I test missing, malformed, expired, revoked, wrong-audience, wrong-issuer, and insufficient credential conditions supported by the system. I verify session or token lifecycle, secure transport, error behavior, and safe logging. I separate identity failure from permission failure.
Q8: How do you test authorization?
I build an actor-resource-action matrix for roles, tenants, ownership, and states. I attempt direct access by changing object identifiers and calling restricted functions, including bulk and nested endpoints. I verify denial, no side effect, safe response, and an appropriate audit trail.
Q9: What is contract testing?
Contract testing verifies that a provider and consumer agree on the interactions the consumer requires. Consumer-driven contracts can run in delivery pipelines and catch incompatible changes before broad integration. They complement rather than replace deployed integration and end-to-end testing.
Q10: What is schema validation?
Schema validation checks structural constraints such as required fields, types, formats, ranges, and additional properties. It catches contract drift efficiently but cannot prove semantic correctness. I pair it with domain assertions and state verification.
Q11: How do you test negative scenarios?
I derive cases from input classes, boundaries, state rules, permissions, protocol requirements, dependencies, and historical failures. Each negative case targets a mechanism and has an expected error plus no unintended side effect. Random invalid payloads alone provide weak coverage and diagnosis.
Q12: How do you test pagination?
I test empty, first, middle, and final pages, size boundaries, invalid cursors, and deterministic ordering. I check duplicates and omissions while records are inserted or deleted, plus authorization filtering and metadata. Cursor and offset designs need different consistency expectations, so I use the documented contract.
Q13: How do you test sorting and filtering?
I cover each field, direction, default, multiple filters, combinations, boundaries, nulls, case, Unicode, time zones, and unsupported values. I verify stable tie-breaking so pagination does not duplicate or lose items. Permission filtering must occur before sensitive results become visible.
Q14: How do you test file upload APIs?
I validate allowed media types, actual content, name, size boundaries, empty and corrupt files, duplicate upload, interruption, and metadata. Security cases include path handling, malware controls, decompression risk, authorization, storage access, and unsafe rendering. I verify cleanup and asynchronous processing states.
Q15: How do you test rate limiting?
I use an approved isolated environment and bounded traffic to test threshold, scope, fairness, response contract, retry guidance, and recovery. I examine per-user, token, IP, tenant, or endpoint policy as documented and check distributed consistency. Functional boundary testing is separate from capacity or denial-of-service work.
Q16: How do you test API versioning?
I keep representative consumers on supported versions and validate requests, responses, errors, defaults, and events. I test upgrade, backward compatibility, additive fields, deprecation signals, mixed-version accounts, and rollback. Compatibility includes meaning, not only schema shape.
Q17: What is the difference between mocks, stubs, and service virtualization?
A stub returns configured responses, while a mock also verifies expected interactions in common testing vocabulary. Service virtualization simulates a broader dependent service with protocols, state, and failure behavior. Terminology varies, so I explain the capability, fidelity, and drift risk rather than relying on labels alone.
Q18: How do you test webhooks?
I verify signature handling against the raw body, correct and rotated secrets, duplicates, delay, reordering, retries, and consumer failures. Processing must be idempotent and observable, with replay and reconciliation for missed outcomes. A successful acknowledgement does not alone prove the downstream business effect.
Q19: How do you test asynchronous APIs returning 202?
I separate request acceptance from eventual completion and verify the operation identity or status contract. I test pending, success, failure, timeout, cancellation, repeated polling, missing work, and authorization. Events or callbacks also need duplicate, order, retry, and reconciliation coverage.
Q20: How do you test timeouts and retries?
I control dependency latency and failure so tests do not sleep unpredictably. I verify timeout boundaries, cancellation, safe retry eligibility, attempt limits, backoff, jitter, server guidance, and preserved first-failure evidence. Mutating retries require an idempotency contract to avoid duplicate work.
Q21: How do you test concurrency?
I identify the invariant and create controlled competing operations, such as two updates with one version or two reservations for the last item. I coordinate start points, capture each response, and verify final durable state, events, and absence of lost or duplicate effects. Repetition without deterministic coordination is useful for stress but weak for exact diagnosis.
Q22: How do you test caching?
I verify cacheability policy, key dimensions, freshness, expiration, validators, invalidation, authorization separation, and behavior on cache failure. I test stale reads after mutation and prevent one tenant's response from serving another. Cache unavailability should normally degrade performance rather than correctness.
Q23: How do you test an API database migration?
I validate schema and data transformation, counts, uniqueness, relationships, precision, defaults, and old and new application compatibility. Tests include restart, rollback, partial migration, concurrent writes, large data, and reconciliation. I preserve privacy and verify audit evidence without copying unsafe production data.
Q24: What makes API automation maintainable?
Maintainable automation exposes business intent, controls data, and produces useful diagnostics. It separates transport configuration, domain clients, builders, fixtures, and oracles without excessive abstraction. Tests are parallel-safe, reviewed, owned, and removed when their signal no longer justifies cost.
Q25: How do you manage API test data?
I create minimal valid resources through supported interfaces or deliberate fixtures and give tests unique identifiers or namespaces. Reference data is immutable or versioned, while cleanup is idempotent and cannot harm other workers. Sensitive production data is not copied casually, and generated data preserves only necessary shape.
Q26: How do you debug an intermittent API failure?
I preserve request, response, timing, environment, build, data identity, and correlation IDs from the first failure. I trace the request through gateway, service, dependencies, storage, and events, then compare passing and failing timelines. I form a falsifiable hypothesis and vary one factor rather than adding retries blindly.
Q27: How do you performance test an API?
I define whether the goal is capacity, regression, endurance, scalability, or resilience, then model representative operations and arrival patterns. I measure latency percentiles, throughput, errors, and saturation under a controlled environment and validated successful workload. I correlate client and server evidence to identify the bottleneck.
Q28: What is API fuzz testing?
Fuzz testing generates or mutates inputs to discover crashes, hangs, unsafe parsing, and violated invariants. Effective fuzzing understands the protocol enough to reach meaningful code and preserves a seed or minimal failing input for reproduction. It complements designed boundary, security, and stateful tests.
Q29: How do you test GraphQL APIs?
I validate schema, queries, mutations, variables, fragments, aliases, nullability, errors, authorization at fields and objects, batching, depth or complexity controls, and resolver behavior. A 200 response can contain GraphQL errors, so I inspect both data and errors. I also test over-fetching, sensitive fields, caching, and performance of nested queries.
Q30: How would you create an API test strategy?
I start with consumers, business invariants, trust boundaries, dependencies, data, and failure cost. I allocate unit, component, contract, integration, end-to-end, security, performance, and production evidence according to risk and feedback speed. The strategy includes environments, ownership, diagnostics, release gates, residual risk, and a plan to improve from incidents.
Common Mistakes
- Checking only HTTP status and a few response fields.
- Confusing authentication with object and function authorization.
- Declaring every POST idempotent without an application contract.
- Prescribing one status code without reading the documented error model.
- Using random invalid input without a rule, mechanism, or oracle.
- Validating schema while ignoring incorrect domain values and side effects.
- Assuming asynchronous events arrive exactly once and in order.
- Retrying mutating requests without a stable operation identity.
- Building one generic request helper that hides endpoint contracts.
- Sharing mutable test data across parallel workers.
- Logging tokens or personal data in test reports.
- Treating mocks as proof of deployed integration.
- Reporting average latency without errors, throughput, and percentiles.
- Running rate or load tests without authorization and stop conditions.
- Naming many tools while being unable to design or debug one complete suite.
Conclusion
The top API testing interview questions reward complete engineering reasoning. Master HTTP semantics, then connect contracts to business state, authorization, failure, compatibility, automation, performance, and safe operational evidence.
Run the local Node.js exercise, extend it with a changed-payload idempotency test, and practice all 30 answers with one API from your own project. Concrete invariants and observed evidence will make your responses more credible than memorized tool syntax.
Interview Questions and Answers
What is API testing?
API testing validates an interface's protocol contract, business behavior, security, reliability, and operational evidence. It sends requests or messages directly and checks responses, durable state, side effects, and failure behavior. The goal is trustworthy consumer outcomes, not merely successful HTTP calls.
What is the difference between API testing and UI testing?
API testing exercises service interfaces directly, so it is usually faster and more controllable for rules, data, and failures. UI testing validates presentation, browser behavior, accessibility, and complete user journeys. A layered strategy uses both according to the risk rather than replacing one with the other.
What should you validate in an API response?
I validate status, headers, media type, schema, field values, relationships, ordering, and the documented error model. For mutations, I also verify durable state and emitted effects. I check that sensitive data is absent and diagnostics such as correlation IDs are useful.
Explain GET, POST, PUT, PATCH, and DELETE.
`GET` retrieves, `POST` submits for resource-specific processing, `PUT` creates or replaces a target representation, `PATCH` partially modifies, and `DELETE` removes the target effect. `GET`, `PUT`, and `DELETE` have idempotent semantics, while `POST` and some patch operations need application-specific protection. I still test the documented behavior because implementations can violate intended semantics.
What is idempotency?
Idempotency means repeating one logical operation does not create an unintended additional effect. For a mutation, a client can provide an operation key that the server binds to account, input, and result according to its contract. I test identical retry, concurrent retry, changed input, ambiguous failure, retention, and durable state.
What is the difference between 401 and 403?
`401 Unauthorized` indicates that valid authentication credentials are missing or not accepted, despite the historical name. `403 Forbidden` means the server understands the identity but refuses the requested action. Some APIs return `404` to conceal resource existence, so I follow the security contract consistently.
How do you test authentication?
I test missing, malformed, expired, revoked, wrong-audience, wrong-issuer, and insufficient credential conditions supported by the system. I verify session or token lifecycle, secure transport, error behavior, and safe logging. I separate identity failure from permission failure.
How do you test authorization?
I build an actor-resource-action matrix for roles, tenants, ownership, and states. I attempt direct access by changing object identifiers and calling restricted functions, including bulk and nested endpoints. I verify denial, no side effect, safe response, and an appropriate audit trail.
What is contract testing?
Contract testing verifies that a provider and consumer agree on the interactions the consumer requires. Consumer-driven contracts can run in delivery pipelines and catch incompatible changes before broad integration. They complement rather than replace deployed integration and end-to-end testing.
What is schema validation?
Schema validation checks structural constraints such as required fields, types, formats, ranges, and additional properties. It catches contract drift efficiently but cannot prove semantic correctness. I pair it with domain assertions and state verification.
How do you test negative scenarios?
I derive cases from input classes, boundaries, state rules, permissions, protocol requirements, dependencies, and historical failures. Each negative case targets a mechanism and has an expected error plus no unintended side effect. Random invalid payloads alone provide weak coverage and diagnosis.
How do you test pagination?
I test empty, first, middle, and final pages, size boundaries, invalid cursors, and deterministic ordering. I check duplicates and omissions while records are inserted or deleted, plus authorization filtering and metadata. Cursor and offset designs need different consistency expectations, so I use the documented contract.
How do you test sorting and filtering?
I cover each field, direction, default, multiple filters, combinations, boundaries, nulls, case, Unicode, time zones, and unsupported values. I verify stable tie-breaking so pagination does not duplicate or lose items. Permission filtering must occur before sensitive results become visible.
How do you test file upload APIs?
I validate allowed media types, actual content, name, size boundaries, empty and corrupt files, duplicate upload, interruption, and metadata. Security cases include path handling, malware controls, decompression risk, authorization, storage access, and unsafe rendering. I verify cleanup and asynchronous processing states.
How do you test rate limiting?
I use an approved isolated environment and bounded traffic to test threshold, scope, fairness, response contract, retry guidance, and recovery. I examine per-user, token, IP, tenant, or endpoint policy as documented and check distributed consistency. Functional boundary testing is separate from capacity or denial-of-service work.
How do you test API versioning?
I keep representative consumers on supported versions and validate requests, responses, errors, defaults, and events. I test upgrade, backward compatibility, additive fields, deprecation signals, mixed-version accounts, and rollback. Compatibility includes meaning, not only schema shape.
What is the difference between mocks, stubs, and service virtualization?
A stub returns configured responses, while a mock also verifies expected interactions in common testing vocabulary. Service virtualization simulates a broader dependent service with protocols, state, and failure behavior. Terminology varies, so I explain the capability, fidelity, and drift risk rather than relying on labels alone.
How do you test webhooks?
I verify signature handling against the raw body, correct and rotated secrets, duplicates, delay, reordering, retries, and consumer failures. Processing must be idempotent and observable, with replay and reconciliation for missed outcomes. A successful acknowledgement does not alone prove the downstream business effect.
How do you test asynchronous APIs returning 202?
I separate request acceptance from eventual completion and verify the operation identity or status contract. I test pending, success, failure, timeout, cancellation, repeated polling, missing work, and authorization. Events or callbacks also need duplicate, order, retry, and reconciliation coverage.
How do you test timeouts and retries?
I control dependency latency and failure so tests do not sleep unpredictably. I verify timeout boundaries, cancellation, safe retry eligibility, attempt limits, backoff, jitter, server guidance, and preserved first-failure evidence. Mutating retries require an idempotency contract to avoid duplicate work.
How do you test concurrency?
I identify the invariant and create controlled competing operations, such as two updates with one version or two reservations for the last item. I coordinate start points, capture each response, and verify final durable state, events, and absence of lost or duplicate effects. Repetition without deterministic coordination is useful for stress but weak for exact diagnosis.
How do you test caching?
I verify cacheability policy, key dimensions, freshness, expiration, validators, invalidation, authorization separation, and behavior on cache failure. I test stale reads after mutation and prevent one tenant's response from serving another. Cache unavailability should normally degrade performance rather than correctness.
How do you test an API database migration?
I validate schema and data transformation, counts, uniqueness, relationships, precision, defaults, and old and new application compatibility. Tests include restart, rollback, partial migration, concurrent writes, large data, and reconciliation. I preserve privacy and verify audit evidence without copying unsafe production data.
What makes API automation maintainable?
Maintainable automation exposes business intent, controls data, and produces useful diagnostics. It separates transport configuration, domain clients, builders, fixtures, and oracles without excessive abstraction. Tests are parallel-safe, reviewed, owned, and removed when their signal no longer justifies cost.
How do you manage API test data?
I create minimal valid resources through supported interfaces or deliberate fixtures and give tests unique identifiers or namespaces. Reference data is immutable or versioned, while cleanup is idempotent and cannot harm other workers. Sensitive production data is not copied casually, and generated data preserves only necessary shape.
How do you debug an intermittent API failure?
I preserve request, response, timing, environment, build, data identity, and correlation IDs from the first failure. I trace the request through gateway, service, dependencies, storage, and events, then compare passing and failing timelines. I form a falsifiable hypothesis and vary one factor rather than adding retries blindly.
How do you performance test an API?
I define whether the goal is capacity, regression, endurance, scalability, or resilience, then model representative operations and arrival patterns. I measure latency percentiles, throughput, errors, and saturation under a controlled environment and validated successful workload. I correlate client and server evidence to identify the bottleneck.
What is API fuzz testing?
Fuzz testing generates or mutates inputs to discover crashes, hangs, unsafe parsing, and violated invariants. Effective fuzzing understands the protocol enough to reach meaningful code and preserves a seed or minimal failing input for reproduction. It complements designed boundary, security, and stateful tests.
How do you test GraphQL APIs?
I validate schema, queries, mutations, variables, fragments, aliases, nullability, errors, authorization at fields and objects, batching, depth or complexity controls, and resolver behavior. A `200` response can contain GraphQL errors, so I inspect both data and errors. I also test over-fetching, sensitive fields, caching, and performance of nested queries.
How would you create an API test strategy?
I start with consumers, business invariants, trust boundaries, dependencies, data, and failure cost. I allocate unit, component, contract, integration, end-to-end, security, performance, and production evidence according to risk and feedback speed. The strategy includes environments, ownership, diagnostics, release gates, residual risk, and a plan to improve from incidents.
Frequently Asked Questions
What should I study for an API testing interview?
Study HTTP, REST constraints, request and response validation, authentication, authorization, schemas, contracts, idempotency, pagination, errors, reliability, performance, security, automation design, and debugging. Practice with a real service so you can explain evidence.
Are status codes enough for API testing?
No. Validate the response contract, business state, side effects, persistence, emitted events, permissions, observability, and behavior on retries. A correct status can still hide incorrect data or duplicate work.
Which API automation tool should I learn?
Choose one that fits your language and team, such as REST Assured, Playwright request contexts, Supertest, pytest with an HTTP client, or Karate. Interview strength comes from design and debugging, not tool count.
How do I prepare API security questions?
Practice broken object authorization, broken function authorization, authentication flaws, excessive data exposure, input attacks, rate abuse, unsafe consumption, and secret handling. Test safely in authorized environments.
What is the difference between schema and contract testing?
A schema checks structural rules such as fields and types. A contract captures an interaction expectation between a consumer and provider, including request, response, and sometimes state, then verifies compatibility in delivery.
How should I answer an API test strategy question?
Start with consumers, business invariants, trust boundaries, dependencies, and failure cost. Then select unit, component, contract, integration, end-to-end, security, performance, and production evidence proportionally.
Do API interview answers need code?
Many interviews include a coding or automation task, so practice creating requests, parsing JSON, asserting contracts and state, handling setup, and producing useful failure output. Write complete, executable examples rather than isolated assertion fragments.
Related Guides
- API Test Engineer Interview Questions and Answers (2026)
- API Testing Interview Questions and Answers (2026)
- Top 30 Automation Testing Interview Questions and Answers (2026)
- API Testing Interview Questions for 7 Years Experience
- API testing Scenario-Based Interview Questions and Answers (2026)
- Top 30 Agile Interview Questions and Answers (2026)