Resource library

Automation Interview

API Testing Interview Questions and Answers: REST, Auth, Contracts (2026)

Master API testing interview questions and answers covering REST, authentication, contracts, GraphQL, negative tests, automation, and senior scenarios.

52 min read | 8,107 words

TL;DR

Strong API interview answers connect HTTP and interface rules to business risk. Explain the request, identity, state, assertions, negative cases, and diagnostic evidence, then state any consistency or compatibility trade-off.

Key Takeaways

  • Connect every status and schema assertion to a business guarantee.
  • Test authentication, authorization, ownership, and tenant isolation separately.
  • Design negative cases from boundaries, state transitions, and trust boundaries.
  • Use contracts for compatibility feedback, then retain focused integration coverage.
  • Treat retries, idempotency, ordering, and eventual consistency as explicit guarantees.
  • Make automation deterministic with owned data, bounded waits, and sanitized evidence.
  • Answer interview scenarios with a rule, example, assertions, risk, and trade-off.

API testing interview questions and answers usually test whether you can reason about behavior, risk, and evidence, not whether you memorized status codes. A strong candidate can translate a business rule into requests, assertions, negative cases, contract checks, and useful diagnostics.

This guide gives you 60 model answers across REST, authentication, data, automation, contracts, GraphQL, asynchronous APIs, performance, security, and test strategy. Use each answer as a reasoning pattern, then replace the examples with systems you have actually tested.

TL;DR

Topic Question count Difficulty
REST and HTTP semantics 6 Beginner to intermediate
Test design and negative testing 6 Intermediate
Authentication and authorization 6 Intermediate to advanced
Data, schemas, and contracts 6 Intermediate to advanced
Automation architecture 6 Intermediate to advanced
GraphQL testing 6 Intermediate
Webhooks and event-driven APIs 6 Advanced
Reliability and performance 6 Advanced
Security testing 6 Advanced
Strategy, debugging, and leadership 6 Senior

For preparation, practice explaining what you would send, what you would assert, what failure you are trying to expose, and how the test remains deterministic. The strongest answer connects protocol rules to product risk and distinguishes a client error from a server defect.

1. REST and HTTP Semantics: API Testing Interview Questions and Answers

Q: What is API testing, and how is it different from UI testing?

API testing calls a service interface directly and verifies its observable contract: status, headers, body, side effects, latency, and error behavior. It isolates business logic from browser rendering, so failures are usually faster to reproduce and diagnose than end-to-end UI failures. It can also exercise states that are awkward to reach through a screen, such as malformed payloads, expired tokens, or concurrent updates. UI tests still matter for layout and integrated user journeys, but a balanced test pyramid places most business-rule coverage below the UI.

Q: What does REST mean in practical testing terms?

REST is an architectural style in which resources are addressed by identifiers and manipulated through a uniform HTTP interface. In testing, I check whether URIs represent nouns, methods carry their defined semantics, representations are negotiated correctly, and each request contains enough context to be understood. I also verify cache controls, stateless authentication, links or identifiers that let clients navigate, and consistent errors. An endpoint can return JSON over HTTP without being well-designed REST, so I test the actual published contract rather than awarding a REST label automatically.

Q: How do you decide whether an endpoint should return 200, 201, 202, or 204?

I map the code to what happened. A successful read or update with a response representation commonly returns 200. Resource creation returns 201 when the resource exists now, ideally with a Location header pointing to it. Accepted work that continues asynchronously returns 202 and should expose a status resource or another completion signal. A successful operation with intentionally no response body can use 204. I assert the body rule too: a 204 response must not carry content, while a 201 response should make the created resource discoverable.

Q: What is the difference between PUT and PATCH, and how would you test it?

PUT conventionally replaces the selected resource representation and is idempotent, while PATCH applies a partial change described by the request document. I create a resource with several fields, send PUT without one optional field, and verify whether the documented replacement semantics remove or default it. For PATCH, I change one field and confirm untouched fields remain stable. I repeat identical requests to verify idempotency, test immutable fields, null versus omission, invalid patch paths or operations, and concurrent updates protected by ETags or version numbers.

Q: What makes an HTTP method safe or idempotent?

A safe method is intended only to retrieve information, so GET, HEAD, and OPTIONS should not create externally visible business changes. An idempotent method may change state, but repeating the same request has the same intended effect as sending it once; PUT and DELETE are typical examples. Idempotency does not require byte-identical responses because timestamps or audit records may differ. I test the business state after retries, not only status codes, and inspect unexpected side effects such as duplicate payments, multiple emails, or repeated inventory decrements.

Q: How do you test caching behavior?

I first identify whether the response is public, private, or prohibited from caching, then inspect Cache-Control, Expires, Vary, ETag, and Last-Modified. I send a conditional request with If-None-Match or If-Modified-Since and expect 304 with no representation when the resource is unchanged. After a mutation, I confirm the validator changes and stale content is not served beyond the documented policy. I also vary authorization, locale, encoding, and query parameters to catch cache-key mistakes that can leak one user's response to another.

2. Test Design and Negative API Testing Interview Questions and Answers

Q: How do you derive API test cases from a specification?

I build a coverage model from resources, operations, parameters, schemas, business invariants, identities, and state transitions. For every input I partition valid, invalid, boundary, absent, null, duplicated, and conflicting values. Then I add cross-field rules, permission matrices, replay and concurrency cases, plus downstream failure behavior. The OpenAPI document supplies mechanical constraints, but examples and business rules often reveal requirements the schema cannot express. I trace high-risk cases to requirements and keep exploratory charters for ambiguity the specification misses.

Q: What negative tests would you run for a create-user endpoint?

I test missing required fields, explicit nulls, empty and whitespace-only strings, malformed email addresses, Unicode, maximum lengths, unsupported properties, wrong JSON types, duplicate identifiers, and violated password policy. I also send malformed JSON, incorrect Content-Type, oversized bodies, expired credentials, insufficient roles, and requests above the rate limit. Cross-field cases matter, such as a country paired with an invalid postal format. For each rejection I assert no user or partial dependent record was created, sensitive values are absent from errors, and the error code and field path are stable.

Q: How do boundary value analysis and equivalence partitioning apply to APIs?

Equivalence partitioning groups inputs expected to behave alike, such as supported currencies, unsupported currencies, and missing currency. Boundary analysis targets transition points where defects cluster. For an allowed quantity of 1 through 100, I would test 0, 1, 2, 99, 100, and 101, then add type and precision cases if JSON numbers are accepted. I apply the same idea to page sizes, date ranges, string lengths, array counts, file sizes, and rate windows. Representative partitions reduce redundant cases without sacrificing deliberate edge coverage.

Q: How do you test pagination?

I verify default and maximum page sizes, first and last pages, an empty collection, a single item, exact page boundaries, invalid cursors, and stable ordering. I traverse every page and assert there are no duplicates or missing identifiers. For cursor pagination, I treat the cursor as opaque and test expiry or tampering according to the contract. I also insert or delete records between requests to understand consistency guarantees. Offset pagination may drift under writes, while a well-designed cursor anchored to a deterministic sort key should provide more stable traversal.

Q: How do you test filtering, sorting, and search parameters?

I seed records that differ in one controlled property, then verify each filter independently and in meaningful combinations. Sorting checks include ascending, descending, ties, null values, case handling, and a deterministic secondary key. Search cases cover exact and partial matches, normalization, punctuation, Unicode, reserved URL characters, and empty queries. I confirm unknown fields and unsupported operators return a documented client error instead of being silently ignored. Finally, I compare metadata such as total counts with the actual filtered set and test authorization before filtering to prevent inference leaks.

Q: How should an API return validation errors?

A useful error is machine-readable, stable, safe, and actionable. I expect an appropriate 4xx status, a durable application code, a human message, field or JSON Pointer location, and a correlation identifier when support needs it. Multiple independent input defects may be returned together if the contract promises that behavior. I reject stack traces, SQL fragments, secrets, and inconsistent shapes. Tests should assert structural fields and durable codes rather than exact prose, unless message wording itself is a localized product requirement.

3. Authentication and Authorization

Q: What is the difference between authentication and authorization?

Authentication establishes who or what the caller is, while authorization decides what that principal may do to a particular resource. I test them separately: missing, malformed, expired, or invalid credentials should fail identity checks; a valid low-privilege credential should reach the permission decision and be denied when appropriate. This distinction helps diagnose 401 versus 403 behavior and exposes broken access control. A complete matrix includes anonymous users, owners, non-owners, support roles, administrators, service accounts, disabled identities, and tenant boundaries.

Q: How do you test bearer token authentication?

I cover missing tokens, wrong schemes, malformed tokens, invalid signatures, wrong issuer or audience, expiry, not-before time, revoked sessions, and insufficient scopes. I never hard-code long-lived production credentials in source control; tests obtain short-lived tokens from a controlled identity environment or inject secrets through CI. Logs and reports must redact Authorization headers. I also validate clock-skew policy near temporal boundaries and ensure a token for one environment, tenant, client, or API cannot be replayed successfully in another.

Q: Explain OAuth 2.0 flows relevant to API testing.

Authorization Code with PKCE is appropriate for interactive public clients, while Client Credentials represents machine-to-machine access without a user. Device Authorization supports input-constrained devices, and refresh tokens obtain new access tokens under server policy. In tests, I verify redirect URI matching, PKCE verifier binding, state handling by the client, audience, scopes, consent, refresh rotation, revocation, and reuse detection. OAuth delegates authorization and does not itself define user identity; OpenID Connect adds ID tokens and identity claims. I avoid the obsolete implicit and password grants in new systems.

Q: How would you test role-based and resource-level authorization?

I create a subject-by-action-by-resource matrix. Roles alone are insufficient because an ordinary user may read their own invoice but not another user's invoice, and a tenant admin must remain inside their tenant. I call the same endpoint with controlled identities against owned, unowned, cross-tenant, nonexistent, and guessed identifiers. Denial must protect both the response and side effects. I also check list endpoints, exports, nested resources, bulk operations, alternate methods, and indirect object references because inconsistent enforcement often appears outside the obvious detail route.

Q: What are common JWT testing mistakes?

The largest mistake is decoding a JWT and treating readable claims as proof of validity. The service must verify the allowed algorithm, signature, issuer, audience, lifetime, and relevant key, then apply authorization to trusted claims. I test algorithm confusion defenses, unknown key IDs, duplicate or malformed claims, excessive clock skew, and key rotation. I do not modify a token and expect it to remain valid. I also check that sensitive data is not placed in the payload, because signed JWT content is commonly encoded rather than encrypted.

Q: How do you test API key authentication securely?

I verify the accepted transport, usually a documented header, and reject keys in query strings if they can leak through histories and logs. Cases include absent, malformed, unknown, disabled, expired, rotated, and scope-limited keys. I confirm per-key rate limits and tenant isolation, redact keys from telemetry, and ensure only a digest or protected value is stored server-side. Rotation deserves a transition test: the new key works, the old key overlaps only for the promised window, then the old key fails without interrupting unrelated clients.

4. Data Validation, Schemas, and Contract Testing

Q: What is schema validation, and what does it not prove?

Schema validation checks structural rules such as required properties, types, formats, enumerations, ranges, and whether unknown properties are allowed. It quickly detects accidental contract drift, but it does not prove business correctness. An order can match JSON Schema while its total is wrong, its customer owns no quoted account, or its state transition is illegal. I combine schema checks with semantic assertions, database or downstream evidence when justified, and invariants across calls. I also pin the intended schema dialect because validator behavior differs across drafts and format checks may be optional.

Q: What is contract testing?

Contract testing verifies that a provider and its consumers agree on request and response interactions without requiring every service to run in one end-to-end environment. Consumer-driven contracts capture examples a consumer actually relies on, then provider verification replays them against the provider. Provider schema conformance offers broader interface rules but may not express consumer assumptions. I use contracts to get rapid compatibility feedback, not to replace integration, security, or business-flow tests. The API contract testing with Pact guide covers broker workflows and provider states in depth.

Q: How do you prevent brittle response assertions?

I assert only behavior guaranteed by the contract. For unordered collections I compare by stable identifiers or sets, not array position. I use tolerant assertions for optional additive fields, dynamic timestamps, generated IDs, and decimal representations while remaining strict about business-critical values and forbidden data. Snapshotting entire responses is convenient but can create noisy changes and hide important review decisions. A focused assertion says why a field matters. When exact ordering, precision, or formatting is contractual, I make that strictness explicit instead of normalizing away a genuine defect.

Q: How do you test backward compatibility?

I inventory existing consumers and compare the proposed contract against the released one. Removing or renaming fields, adding new required inputs, narrowing accepted values, changing types, altering defaults, or changing error semantics can break clients. Additive optional response fields are often compatible, but clients with strict deserializers may still fail, so contract evidence matters. I run old client contracts against the candidate provider and test version negotiation. Deprecation should include telemetry, documentation, a communicated deadline, and a migration path rather than an abrupt version switch.

Q: How do you test date, time, and numeric fields?

I use explicit instants around UTC midnight, daylight-saving transitions, leap days, offset boundaries, and allowed precision. RFC 3339 strings should carry an offset or Z when they represent an instant; a local business date should not be silently converted into a timestamp. Numeric tests include zero, negative values, min and max, decimal scale, rounding mode, and values beyond JavaScript's safe integer range. Money should follow the contract's representation, often minor units or decimal strings, because binary floating-point comparisons can produce false results and real accounting defects.

Q: What should be tested for file upload and download APIs?

Uploads need valid files, empty files, maximum boundaries, mismatched extensions and media types, malformed multipart boundaries, duplicate parts, unsafe names, interrupted streams, and malware-processing states. I verify the server inspects content rather than trusting Content-Type and stores files outside executable paths. Downloads require authorization, correct media type, Content-Disposition, length or streaming behavior, checksum integrity, range requests if supported, and safe names. I also test deleted or quarantined objects and ensure cross-tenant identifiers cannot expose another customer's file.

5. API Automation Architecture and Tooling

Q: What belongs in a maintainable API automation framework?

I separate transport concerns, domain actions, data builders, assertions, environment configuration, and test cases. A thin client owns base URLs, headers, serialization, timeouts, retries, and sanitized logging. Domain helpers express operations such as createOrder rather than hiding assertions inside a generic request wrapper. Builders create readable valid defaults that each test overrides deliberately. The suite needs isolated data, parallel-safe cleanup, deterministic clocks where possible, tagged execution, useful failure artifacts, and contract or schema support. Tool choice matters less than keeping business intent visible.

Q: Show a simple API test using Node's current built-in APIs.

Node's built-in test runner and fetch API can create a dependency-free smoke test. The base URL stays configurable, the request has an explicit abort deadline, and the assertions validate both protocol and business data.

import test from "node:test";
import assert from "node:assert/strict";

test("GET /health reports readiness", async () => {
  const baseUrl = process.env.API_BASE_URL ?? "http://localhost:3000";
  const response = await fetch(`${baseUrl}/health`, {
    signal: AbortSignal.timeout(3000),
    headers: { Accept: "application/json" }
  });

  assert.equal(response.status, 200);
  assert.match(response.headers.get("content-type") ?? "", /application\/json/);
  const body = await response.json();
  assert.equal(body.status, "ready");
});

I would keep a liveness test separate from readiness because a running process may still lack its database or queue connection.

Q: How do you manage test data?

I prefer creating data through public APIs or dedicated test fixtures with unique run identifiers. Each test owns what it creates and records identifiers for cleanup, which enables parallel execution and avoids dependence on execution order. Fixed seed data is useful for immutable reference values, but shared mutable accounts create collisions. Cleanup should be idempotent and run even after failure; time-to-live cleanup handles interrupted jobs. Direct database writes are reserved for states that cannot reasonably be created otherwise, and those helpers must preserve constraints so tests do not exercise impossible production states.

Q: Should API tests retry failures?

I retry only operations whose semantics and failure mode make retry safe. A transport reset before a response may justify a limited retry for GET, while retrying a payment POST without an idempotency key can duplicate a charge. Assertion failures should not be retried because that hides defects. The framework should record every attempt, apply bounded backoff with jitter where appropriate, honor Retry-After, and keep a total deadline. I distinguish product retry behavior from test-runner reruns: the former is a feature under test, while the latter can mask flaky infrastructure.

Q: How do you run API tests in CI?

I run fast deterministic checks on pull requests, then broader integration, contract, and environment-dependent suites at suitable gates. CI provisions known configuration, obtains short-lived credentials, waits on explicit readiness, and publishes sanitized request-response evidence plus machine-readable results. Tests are sharded only when data ownership permits it. A failed gate must identify whether setup, service behavior, or assertions caused the failure. I also quarantine only with an owner and expiry date, monitor duration and flake rate, and never treat repeated reruns as a substitute for fixing nondeterminism.

Q: Postman, REST Assured, Playwright request context, or a language HTTP client?

I choose based on the team and testing layer. Postman is accessible for exploration and shared collections, with Newman or the Postman CLI for automation. REST Assured fits Java ecosystems and provides expressive HTTP assertions. Playwright's APIRequestContext is useful when API setup and browser journeys share authentication and lifecycle. A native HTTP client offers maximum control and minimal abstraction. The decision considers reviewability, type safety, parallelism, secret handling, reporting, contract support, and ownership. The Postman API testing tutorial and JavaScript API framework guide show two practical approaches.

6. GraphQL API Testing

Q: How is GraphQL testing different from REST testing?

GraphQL commonly uses one HTTP endpoint and expresses the operation, fields, arguments, and variables in the request body. HTTP 200 can contain execution errors, so I assert the GraphQL response envelope, data nullability, errors, paths, and extensions rather than relying on status alone. Clients choose response shape, which expands combinations involving aliases, fragments, nested selections, and variables. Schema introspection helps generate checks, but authorization must still be proven at resolver and field level. See the modern GraphQL API testing guide for deeper workflows.

Q: What do you assert in a GraphQL response?

I assert that data matches the requested selection, no unrequested sensitive fields appear, null behavior follows the schema, and errors point to the correct response path. For a successful operation, errors should normally be absent unless partial results are an intentional contract. For a field failure, I verify null propagation through non-null parents and confirm unaffected sibling data remains usable. I also check application error codes in extensions, ordering and pagination semantics, authorization per nested field, and that aliases do not bypass policy or confuse error paths.

Q: How do you test GraphQL queries and variables?

I cover literal and variable inputs, missing required variables, explicit null, wrong scalar types, unknown fields, unknown arguments, invalid enum values, reusable fragments, aliases, and operationName when a document contains multiple operations. Validation errors should occur before resolver side effects. Custom scalars need boundary tests based on their documented coercion rules. I also compare semantically identical requests expressed with whitespace or variable changes and confirm persisted-query handling if enabled. Query generation is useful, but curated business scenarios remain necessary because schema validity cannot prove correct resolver behavior.

Q: How do you test GraphQL mutations?

I assert the mutation's returned object, domain side effect, authorization, and any clientMutationId or idempotency behavior the schema exposes. Inputs receive the same negative and boundary treatment as REST payloads, including omitted versus null fields. I test partial failures in nested input, optimistic concurrency, duplicate submission, and whether errors reveal prohibited resource existence. If a mutation triggers asynchronous work, the immediate payload should expose an identifier or state that can be observed deterministically. Finally, I query the resource independently so the test does not trust only the mutation's echo.

Q: How do you test GraphQL pagination?

For Relay-style connections I validate edges, nodes, pageInfo, cursors, hasNextPage, hasPreviousPage, first, after, last, and before. Traversing the full connection should yield unique nodes in deterministic order. I test empty and single-item connections, exact boundaries, invalid or foreign cursors, deleted anchor records, and concurrent inserts. Cursors remain opaque to clients even if their encoding is obvious. Authorization must occur before counts and page metadata are calculated, otherwise totalCount or cursor behavior can leak the existence of inaccessible records.

Q: What GraphQL security and performance risks would you test?

I test field and object authorization, introspection policy, alias amplification, deeply nested selections, circular relationships, large page sizes, batching, and expensive resolver combinations. The service should use depth, complexity, cost, or allow-list controls appropriate to its clients, but limits must not reject legitimate operations unpredictably. I measure database calls and latency for representative query shapes to expose N+1 behavior. Error messages must not reveal stack traces or schema internals beyond policy. The GraphQL query complexity security guide provides focused attack and limit cases.

7. Webhooks and Event-Driven APIs

Q: How do you test a webhook producer?

I register a controlled receiver, trigger the business event, capture the raw request, and assert method, destination, headers, signature, event identifier, timestamp, version, and payload. Then I exercise 2xx success, timeout, connection reset, 4xx rejection, 429 throttling, and 5xx failure to verify retry policy. Retries should preserve the event identity and avoid silently changing the payload. I also test subscription filtering, disabled endpoints, secret rotation, ordering guarantees, and delivery logs. The webhook API testing complete guide contains a full receiver design.

Q: How do you verify webhook signatures?

The verifier must use the exact raw bytes received, not parsed and reserialized JSON, because whitespace or key ordering can change the digest. I compute the expected HMAC with the documented algorithm, compare it using a timing-safe function, and bind a signed timestamp to a narrow tolerance to reduce replay risk. Tests cover a valid signature, changed body, wrong secret, wrong timestamp, missing components, malformed encoding, and overlapping old and new secrets during rotation. I also ensure proxies do not transform compressed or encoded content before verification.

Q: How do you test retries and duplicate event delivery?

I configure the receiver to fail the first attempts and record arrival times, identifiers, and payload hashes. Then I verify the documented backoff, attempt limit, retryable status classes, and terminal state. Because at-least-once delivery permits duplicates, the consumer should use a durable event or operation key and commit deduplication atomically with its side effect. I send the same event concurrently, after a process restart, and after the deduplication window. The key assertion is one business outcome, not one HTTP request, since multiple deliveries may be correct transport behavior.

Q: What is eventual consistency, and how should tests handle it?

Eventual consistency means a write can succeed before all readable views or downstream services reflect it. A test should observe a documented completion signal or poll a meaningful state with a bounded deadline and interval, not sleep for an arbitrary fixed duration. The failure report should show the last observed state and elapsed time. I test both the normal convergence path and terminal failure or dead-letter behavior. The agreed service objective determines the deadline; endless polling converts a latency defect into a hung test and gives no useful diagnostic evidence.

Q: How do you test message ordering and partitioning?

I publish distinguishable events for the same aggregate and across different aggregates, then inspect the consumer's resulting state. If ordering is guaranteed only within a partition, all events for one entity must use the same partition key and increasing sequence or version. I introduce delayed delivery, duplicates, and out-of-order messages to verify stale updates are rejected or reconciled. Cross-partition global order should not be asserted unless the platform promises it. Rebalancing, consumer restart, and retry topics are essential cases because ordering defects often appear during recovery rather than steady flow.

Q: What should be tested in an event-driven API contract?

I verify event name, version, key, headers, schema, required and optional fields, semantic meanings, and compatibility policy. Producers should not emit undocumented enum values or remove fields consumers rely on. Consumers should tolerate permitted additive fields and handle unknown event types safely. I test tombstones or deletion events, sensitive-data classification, correlation and causation identifiers, and the boundary between publication and the originating transaction. The event-driven API testing guide explains schema registries, replay, dead-letter queues, and asynchronous assertions.

8. Reliability, Rate Limits, and Performance

Q: How do you test API performance?

I define workload from actual or expected operations, payload distributions, concurrency, think time, and authentication behavior. I measure latency percentiles, throughput, error rate, resource saturation, and dependency timing after a warm-up, using a controlled environment and repeatable data. Averages alone hide slow tails, so acceptance criteria should name percentiles and load conditions. I separate load, stress, spike, soak, and capacity questions because each finds different failures. Functional assertions remain active at a sampled rate so a fast stream of error pages is never reported as success.

Q: How do you test rate limiting?

I identify the limit key, window or token-bucket policy, cost model, and scope. Tests send requests just below, at, and above the boundary from one and multiple identities, then verify 429 responses, Retry-After, limit headers if documented, and recovery after refill. I check that failed authentication cannot cheaply exhaust another user's quota and that distributed instances enforce one coherent policy. Bursts and concurrent requests reveal race conditions. Different-cost GraphQL queries or bulk operations may consume more than one unit, so request count alone may not predict the result.

Q: What is an idempotency key, and how do you test it?

An idempotency key lets a client safely retry a non-idempotent operation such as creating a payment. I send concurrent and sequential requests with the same key and identical payload, then assert one business operation and the documented replay response. Reusing the key with a different payload should be rejected rather than silently returning unrelated data. I test scope across users and endpoints, persistence after server restart, expiry, in-progress requests, failures before and after commit, and response replay. The API idempotency testing guide provides detailed race scenarios.

Q: How do you test timeouts and cancellation?

I control a dependency or test endpoint to delay at known stages: before headers, during body streaming, and after a downstream commit. The client or gateway should enforce explicit connect, response, idle, and total deadlines as applicable. Cancellation must release sockets, database work, and other resources, while preserving any operation already committed. I assert the error classification and correlation evidence instead of relying on wall-clock guesses. Retry behavior depends on method semantics and commit knowledge; an unknown payment result should be reconciled by idempotency key, not blindly repeated.

Q: How do you test circuit breakers and resilience behavior?

I make a dependency fail until the breaker crosses its configured threshold, verify the open state fails fast, then confirm limited probes in half-open state and recovery after success. Tests should also cover rolling-window expiry, concurrent callers, slow-call thresholds, and what response the API gives during protection. A fallback must not return stale or fabricated data without a clear contract. I capture dependency call counts to prove the breaker actually reduced traffic. Resilience tests are strongest when the fault is injected precisely rather than inferred from a randomly unstable shared environment.

Q: How do you diagnose intermittent API latency?

I begin with correlated traces and break total time into gateway, application, database, cache, queue, and external calls. I compare slow and normal requests by route, tenant, payload size, cache state, instance, region, connection reuse, and query plan. Percentile time series and exemplars are more useful than a single average. Controlled repetitions can isolate cold starts, garbage collection, lock contention, DNS, TLS, pool exhaustion, or N+1 queries. I preserve the exact request identity and timing evidence, because increasing the test timeout only hides the symptom and destroys the signal.

9. API Security Testing Basics

Q: What API security tests should every project include?

At minimum I cover broken object and function authorization, authentication failures, excessive data exposure, mass assignment, injection, unsafe file handling, resource exhaustion, misconfiguration, inventory gaps, and unsafe consumption of upstream data. I derive cases from the system's threat model and data classification rather than running a scanner alone. Tests include horizontal and vertical privilege changes, alternate encodings and methods, bulk endpoints, old API versions, and sensitive fields in errors or logs. The API security testing basics guide provides a practical baseline.

Q: What is mass assignment, and how do you test it?

Mass assignment occurs when a framework binds client JSON directly to an internal model and unintentionally permits protected fields. I take a valid update payload and add properties such as role, tenantId, accountBalance, isVerified, ownerId, or internal status. The server should reject or ignore them according to a documented allow-list, and the persisted record must remain protected. I repeat the attempt through create, update, patch, bulk, nested, and alternate-version endpoints. Response omission is not evidence of safety, so I read the resource with an authorized observer or inspect an appropriate audit record.

Q: How do you test for injection without damaging an environment?

I use an authorized isolated environment, synthetic data, bounded payloads, and monitoring agreed with the service owner. The goal is to prove input is treated as data, not to destroy or extract real records. I target SQL, NoSQL, command, template, header, and log contexts based on the architecture, using harmless predicates, delays within strict limits, or canary values. Parameterized queries and allow-lists are the expected controls. I verify response, side effects, logs, and downstream calls because a generic 500 may hide a real injection path.

Q: How do you test sensitive data exposure?

I build an inventory of fields classified as public, internal, confidential, or regulated and map which identities may receive each one. Then I inspect successful responses, errors, headers, exports, list endpoints, nested GraphQL fields, webhooks, logs, caches, and analytics events. I pay special attention to password hashes, tokens, reset links, personal identifiers, payment data, internal notes, and signed URLs. Field filtering must happen server-side before serialization. Tests also verify cache directives and that low-privilege projections cannot infer hidden values through counts or error differences.

Q: How do you test CORS?

CORS is enforced by browsers, so direct HTTP tools can inspect policy but do not reproduce browser enforcement by themselves. I send preflight OPTIONS requests with allowed and disallowed Origin, method, and requested headers, then verify Access-Control-Allow-* responses, Vary: Origin, credential policy, and maximum age. A credentialed response must not combine a wildcard origin with Access-Control-Allow-Credentials true. I also test simple requests and exact origin parsing, including scheme, port, subdomains, null origins, suffix tricks, and reflected arbitrary origins. CORS does not replace server-side authorization.

Q: What is the security significance of API versioning and inventory?

Unknown, undocumented, or deprecated endpoints often miss current authentication, validation, patching, and monitoring controls. I compare gateway routes, code, OpenAPI documents, DNS hosts, mobile traffic, and observed logs to build an inventory. Old versions receive the same authorization and data-exposure tests as current routes until they are actually removed. I verify deprecation headers and client migration telemetry, then confirm retired endpoints no longer resolve through alternate hosts or methods. An accurate inventory also prevents test plans from protecting only the polished public surface while shadow APIs remain exposed.

10. Strategy, Debugging, and Senior-Level Scenarios

Q: How do you prioritize API test coverage when time is limited?

I rank cases by business impact, likelihood, change scope, exposure, reversibility, and detectability. Authentication, authorization, money movement, destructive operations, and high-volume integrations come before cosmetic metadata. For the changed path I cover a representative success, important boundaries, likely client mistakes, permission denial, dependency failure, and critical side effects. Existing production incidents and traffic show where reality differs from assumptions. I state what remains untested and the residual risk so release decisions are conscious. A large case count is less valuable than a compact suite protecting consequential behavior.

Q: An API returns 500 only in CI. How do you investigate?

I preserve the correlation ID, sanitized request, response, service version, environment configuration, test data identifiers, and timestamps. Then I compare CI with local execution: base URL, DNS, proxy, credentials, time zone, locale, payload encoding, dependency availability, database migrations, and parallelism. Service logs and traces reveal whether the 500 is an application defect or invalid environment state. I reproduce with the exact serialized request, not a hand-built approximation. If concurrency triggers it, I reduce the shard count only as a diagnostic experiment, then fix the underlying shared-state or race defect.

Q: How do you distinguish a product bug from a test bug?

I reproduce the request independently, inspect the published contract, and compare actual state with both the test's assertion and service evidence. A product defect violates a requirement or invariant; a test defect has incorrect expectations, corrupt setup, races, stale data, or misleading parsing. Sometimes the specification is ambiguous, which is a requirement gap rather than proof either side is correct. I minimize the case, freeze dynamic values, and examine raw bytes before abstractions transform them. The final defect report includes observed behavior, expected basis, reproducible inputs, side effects, and correlation evidence.

Q: What makes an API defect report useful?

It names the environment and build, endpoint and method, sanitized headers and body, prerequisites, minimal steps, actual status and response, expected result with a requirement reference, and business impact. Dynamic identifiers, timestamps, correlation IDs, and relevant logs make distributed failures searchable. For asynchronous behavior I include the event timeline and last observed state. I attach a curl reproduction when safe, but remove secrets and personal data. A title such as "PATCH /orders permits shipped-to-draft transition" is far more actionable than "API not working" because it identifies the violated invariant.

Q: How do you test a third-party API integration?

I keep a small provider sandbox suite for genuine compatibility and use a contract-faithful stub for deterministic failure coverage. Tests include authentication, quotas, pagination, timeouts, malformed or additive responses, provider error mapping, retries, idempotency, and webhook verification. I record provider request identifiers for support without logging secrets. The stub must not become an invented ideal, so captured specifications and periodic sandbox checks keep it honest. I also test our behavior when the provider is slow or unavailable and ensure reconciliation can resolve outcomes that remain unknown after a timeout.

Q: What metrics indicate a healthy API test suite?

I track escaped defects by risk area, deterministic pass rate, flaky-test rate, runtime percentiles, time to useful failure diagnosis, requirement and contract coverage, quarantine age, and maintenance cost. Raw test count or line coverage alone can rise while protection falls. I separate product failures from environment and test failures and watch repeated manual reruns. Mutation testing or seeded faults can evaluate whether important assertions detect wrong behavior. The best dashboard supports decisions: where risk lacks coverage, which tests slow feedback, and which failures consume engineering time without finding defects.

Q: How would you explain your API testing strategy in an interview?

I begin with the product's resources, consumers, trust boundaries, business-critical flows, and failure costs. Then I describe layered coverage: schema and unit checks near code, service-level functional and negative tests, consumer contracts, focused integration checks, a few end-to-end journeys, plus performance and security tests based on risk. I explain data isolation, environments, CI gates, observability, and ownership of flaky tests. Finally, I give one concrete example where the strategy caught or prevented a meaningful defect. That evidence demonstrates judgment better than listing every tool I have used.

How Interviewers Grade Your Answers

Interviewers usually grade the structure of your reasoning before they grade tool syntax. Begin by clarifying the contract and business outcome. Name the request, identity, starting state, expected response, and observable side effect. Add a negative or boundary case that targets a realistic failure, then explain how you would keep it repeatable and diagnose it in CI.

A junior answer often stops at "check status code and body." An intermediate answer adds headers, schemas, business rules, test data, authorization, and negative paths. A senior answer discusses competing guarantees, consumer impact, concurrency, observability, rollout compatibility, and risk-based prioritization. Seniority is not measured by making every answer longer. It appears in choosing the few assertions that prove the operation is correct and explaining what those assertions cannot prove.

Use this answer pattern when you need a compact response:

  1. State the rule or guarantee.
  2. Give one concrete request or state setup.
  3. Name protocol and business assertions.
  4. Add the highest-risk negative, permission, or concurrency case.
  5. Explain data isolation and diagnostic evidence.
  6. Mention a trade-off only when it changes the decision.

For coding questions, write complete imports and show error handling, configuration, and cleanup. Avoid fictional helper methods unless you define them. Explain why the assertion matters after showing the code. If you cannot recall a library method, say how you would verify it in official documentation rather than inventing an API.

For scenario questions, ask concise clarifying questions: Is the operation synchronous? Is delivery at least once? What is the idempotency scope? Which identity owns the resource? Are ordering and consistency guaranteed? Interviewers are often checking whether you discover the missing requirement. Do not assume a stronger guarantee than the system promises.

Experience claims should be evidence-based. Instead of saying you "did API automation," describe the scale and problem without exposing confidential details: what interfaces you owned, how tests ran, how data was isolated, what defect escaped or was prevented, and what you changed afterward. A small authentic example with a clear decision is stronger than a catalogue of fashionable tools.

What a complete answer sounds like

Suppose the interviewer asks how you would test POST /payments. A weak response lists a happy path and several status codes. A complete response first clarifies whether the provider creates the charge synchronously, what identifies a duplicate, and which payment states are possible. It creates a controlled customer and funding method, sends an authenticated request with an idempotency key, and asserts the status, representation, persisted payment, ledger effect, and emitted event. It then repeats the request concurrently, changes the payload under the same key, and simulates a timeout after commit. That answer shows HTTP knowledge, financial risk awareness, concurrency reasoning, and a method for resolving an unknown outcome.

For a GET /accounts/{id} authorization question, do not say only that unauthorized users receive 401. Separate an anonymous caller, a user with an invalid token, a valid user requesting another user's account, a support agent with restricted access, and a tenant administrator crossing a tenant boundary. Explain whether forbidden and nonexistent resources intentionally return the same external response to limit enumeration. Check list, export, and nested endpoints too, because protecting the detail route alone is incomplete. This answer demonstrates that you understand identity, permissions, object ownership, information disclosure, and consistent policy enforcement.

If asked about pagination, describe a seeded data set with a deterministic sort key and records on both sides of every boundary. Traverse the collection and compare the union of returned identifiers with the expected set. Add ties, an invalid cursor, an empty last page, and a write between page requests. State whether the service promises snapshot consistency or merely stable forward traversal. This turns a generic answer about page numbers into a test that can expose duplication, omission, drift, and incorrect metadata.

A contract-testing answer earns more credit when it locates the contract in a delivery workflow. Explain that consumer expectations are published, provider verification runs against a candidate build with controlled provider states, and deployment checks consult verification results for the relevant versions. Then name the limits: a verified example does not prove every business rule, production infrastructure, or authorization path. Discuss additive changes, removed fields, new required inputs, and an intentional breaking-change migration. The interviewer can now see that you understand both the technique and its operational value.

For an intermittent failure, structure the response as evidence, hypotheses, experiments, and resolution. Preserve the exact serialized request and correlation ID. Compare passing and failing traces, configuration, data ownership, instance, timing, and concurrency. Change one variable at a time and keep the minimized reproduction. Saying "check the logs" is only a starting point; identifying which evidence will distinguish a service race from a test-data collision demonstrates practical debugging skill.

Depth by experience level

For an entry-level role, accurate HTTP concepts, readable test cases, sensible positive and negative coverage, and basic tool fluency are usually sufficient. You should be able to explain why a request is valid, interpret a response, handle authentication safely, and write assertions that go beyond a status code. Admit what you have not used, then reason from the protocol. Guessing an advanced tool API is worse than giving a correct language-neutral design.

At the intermediate level, expect questions about reusable automation, data isolation, CI, schemas, token scopes, pagination, retries, and environment failures. Interviewers look for independent ownership: can you add coverage without creating shared-state flakes, diagnose a pipeline failure, and decide which assertions belong at service versus UI level? Use examples where you improved feedback or found a boundary defect. Quantify only facts you can defend, and explain how you measured them.

Senior candidates are evaluated on system guarantees and organizational judgment. You may be asked to design coverage for a migration, a payment workflow, a multi-tenant service, or an event-driven integration with incomplete requirements. Discuss consumer compatibility, rollout controls, observability, failure containment, security boundaries, and the residual risk you would communicate. A senior answer should choose priorities under constraints. Attempting to test every combination is not a strategy unless you can explain cost, selection, and expected signal.

For a lead role, include how quality becomes a shared engineering capability. Describe contract ownership, review standards, production feedback, flaky-test governance, reusable infrastructure, and how teams decide release gates. Show that you can challenge an unclear requirement without blocking discovery, and that you can translate a serious incident into focused preventive checks. Leadership is visible in better decisions and feedback loops, not in owning the largest test suite.

Coding exercise evaluation

Before typing, restate the behavior and ask what environment, language version, dependencies, and cleanup rules are available. Keep the example small and executable. Put the base URL and credential outside source code, set a finite deadline, send explicit Accept and Content-Type headers, parse the response safely, and assert business meaning. If the exercise creates data, use a unique value and clean it up. These details distinguish production-minded code from a snippet that passes once on a laptop.

When the service is unavailable or returns non-JSON, the test should fail with useful context rather than throwing an unrelated parsing exception. Capture the status, selected safe headers, and a bounded response excerpt while redacting credentials and personal data. Do not dump everything automatically. Explain whether transport failures, unexpected statuses, and assertion mismatches need different error categories because each sends the investigator to a different layer.

A good abstraction reduces repetition without erasing the request. A helper named request(method, path, body) often moves all meaning into positional arguments and encourages generic assertions. Prefer a small transport client plus domain operations such as createCustomer and cancelOrder, with assertions in the test or focused matchers. The evaluator wants to see that future failures will point to a violated rule, not merely to line 200 of a universal wrapper.

Parallel execution is a common follow-up. Explain how every worker receives unique identities or namespaces, how generated resources are tracked, and how cleanup tolerates already-deleted records. Avoid mutable global tokens and order-dependent fixtures. If the target cannot isolate data, say that parallelism must be limited for that group and identify the product or testability change that would remove the constraint.

Common Mistakes

  • Asserting only 200 and ignoring the response meaning, headers, side effects, and durable state.
  • Treating every 4xx or 5xx as equivalent instead of checking stable application error codes and retryability.
  • Confusing authentication with authorization and never testing a valid user against another user's resource.
  • Reusing one shared mutable account across parallel tests, which creates order dependence and false failures.
  • Adding sleeps for eventual consistency rather than polling a meaningful state under a bounded deadline.
  • Retrying all failures, including assertion failures and unsafe POST requests, until the pipeline turns green.
  • Logging bearer tokens, API keys, cookies, personal data, or complete payloads in CI artifacts.
  • Validating a schema while missing incorrect totals, ownership, state transitions, and other semantic rules.
  • Assuming HTTP 200 means a GraphQL operation succeeded even when the errors array reports resolver failure.
  • Parsing and reserializing a webhook body before signature verification, which changes the signed bytes.
  • Expecting exactly-once delivery from an at-least-once event system instead of making the consumer idempotent.
  • Using production data or sending destructive security payloads without authorization and isolation.
  • Writing one enormous end-to-end suite when focused service and contract tests would fail faster and explain more.
  • Hard-coding generated IDs, current dates, environment URLs, or long-lived credentials into test code.
  • Comparing entire dynamic responses as strings, producing brittle failures for harmless field order or timestamps.
  • Ignoring time zones, decimal precision, Unicode, large integers, and null-versus-omitted semantics.
  • Claiming compatibility because a new schema is additive without running the contracts of strict existing consumers.
  • Measuring only average latency and missing tail behavior, saturation, errors, and incorrect fast responses.
  • Letting quarantined tests remain ownerless, which converts temporary triage into permanent blind spots.
  • Giving memorized definitions without a concrete request, assertion, risk, or diagnostic method.

Keep Practicing

Knowledge becomes interview-ready when you can apply it under a constraint. Open the QAJobFit API testing practice track, answer aloud, and compare your reasoning with the model rather than memorizing its wording.

Continue with focused resources:

Create a short story for each major topic: the risk, the defect, the evidence, and the improvement. Then implement one runnable check, one authorization matrix, one contract verification, and one asynchronous test. That combination prepares you for definition questions, coding exercises, and senior design conversations.

A strong API tester does more than send requests. You make guarantees visible, challenge them at boundaries and trust transitions, and leave evidence that helps a team act quickly.

Interview Questions and Answers

What is API testing?

API testing verifies a service interface directly, including status, headers, representation, business rules, side effects, errors, and nonfunctional behavior. It reaches states that are difficult to exercise through a UI and usually produces faster diagnostic feedback. UI coverage remains necessary for rendering and critical integrated journeys.

What is the difference between PUT and PATCH?

PUT conventionally replaces the selected representation and is idempotent. PATCH applies a partial change expressed by the patch document. I test omission, null, immutable fields, repeated requests, and concurrent update controls because implementations often blur the distinction.

How do you test API authorization?

I build a subject-by-action-by-resource matrix and call each operation with owners, non-owners, tenant peers, cross-tenant users, elevated roles, and disabled identities. I verify both response and side effects. List, bulk, nested, and export endpoints receive the same checks as detail routes.

What is contract testing?

Contract testing checks that a service provider and its consumers agree on their interactions. Consumer-driven contracts capture examples a consumer depends on and replay them during provider verification. They accelerate compatibility feedback but do not replace integration, security, or end-to-end tests.

How do you test negative API cases?

I partition each input into valid, absent, null, malformed, wrong-type, boundary, unsupported, duplicate, and conflicting values. I add identity, permission, state transition, rate, and dependency failures. Every rejected request must leave protected state unchanged and return a safe, stable error.

How do you test an asynchronous API?

I observe a documented completion signal or poll a meaningful state with a bounded deadline. I test successful convergence, timeout, terminal failure, duplicate delivery, ordering guarantees, and recovery. Arbitrary sleeps are avoided because they are slow and nondeterministic.

What should an API automation framework contain?

It should separate transport, domain actions, builders, assertions, configuration, and tests. Data ownership, parallel-safe cleanup, sanitized logging, explicit timeouts, schema support, and useful CI artifacts are essential. Abstractions should keep business intent visible instead of hiding it behind generic helpers.

How do you test GraphQL errors?

I inspect the errors array, data nullability, response path, and stable extension codes even when HTTP status is 200. I verify null propagation through non-null parents and confirm unaffected sibling data behaves as promised. Resolver authorization and partial results need explicit cases.

How do you test webhook signatures?

I calculate the expected signature from the exact raw request bytes and compare it with a timing-safe function. Cases include a changed body, stale timestamp, wrong or rotated secret, missing components, and malformed encoding. Parsing and reserializing JSON before verification is unsafe.

What is idempotency testing?

Idempotency testing proves retries do not create additional business effects. For an idempotency key, I send identical concurrent and sequential requests, verify one operation, and test payload mismatch, scope, expiry, restart, and failures around commit. The business state is more important than identical response bytes.

How do you test API rate limits?

I send traffic below, at, and above the boundary for the documented identity and window. I assert 429 behavior, recovery, Retry-After, concurrency, distributed consistency, and isolation between callers. If requests have different costs, I validate the cost model rather than counting calls only.

How do you prioritize API tests?

I rank coverage by impact, likelihood, exposure, change, reversibility, and detectability. Critical permissions, money movement, destructive actions, and high-volume integrations come first. I communicate the untested residual risk so release decisions are explicit.

Frequently Asked Questions

What should I study for an API testing interview?

Study HTTP semantics, REST resources, status codes, headers, JSON, authentication, authorization, negative testing, schemas, contracts, automation design, GraphQL basics, asynchronous delivery, performance, and security. Practice applying each concept to a concrete endpoint instead of memorizing definitions.

How many API testing questions are in this guide?

The main article contains 60 distinct, fully answered interview questions across ten topic sections. It also includes a grading rubric, common mistakes, practice links, FAQs, and concise model answers.

Which tool is best for API testing interviews?

There is no universal best tool. Use the tool expected by the role, such as Postman, REST Assured, Playwright, or a language HTTP client, but demonstrate protocol knowledge and sound test design that transfer between tools.

How do I answer scenario-based API testing questions?

Clarify the guarantee and starting state, then describe the request, identity, protocol assertions, business side effects, negative cases, and diagnostic evidence. Include concurrency, retries, or eventual consistency only when they affect the scenario.

Is checking the status code enough in API testing?

No. A status code summarizes the outcome but does not prove response data, headers, side effects, authorization, persistence, or downstream behavior. Assert the smallest set of observations that proves the business operation is correct.

What is the difference between API contract and schema testing?

Schema testing validates structural rules for a message. Contract testing verifies an interaction and the assumptions between a consumer and provider, which can include path, method, headers, status, and selected body behavior in addition to schema.

How should experienced testers prepare for API interviews?

Prepare examples involving risk prioritization, framework architecture, CI diagnostics, consumer compatibility, access control, concurrency, resilience, and production incidents. Explain decisions and trade-offs with evidence rather than listing tools.

Related Guides