Common API Testing Interview Questions
Common API Testing Interview Questions Introduction API Testing is one of the most frequently discussed topics in QA and Automation interviews. Interviewers assess not only whether a candidate knows API concepts, but also whether they understand real-world testing practices, HTTP protocols, REST principles, authentication mechanisms, automation frameworks, debugging techniques, security testing, and CI/CD integration. Questions typically progress from basic concepts to scenario-based discussions. Experienced candidates are expected to explain why something is done, not just what it is. This section covers the most commonly asked API Testing interview questions along with concise answers that help build a strong conceptual foundation.
What is an API?
An Application Programming Interface (API) is a set of rules and protocols that allows different software applications to communicate with each other. APIs define how requests are made, how data is exchanged, and how responses are returned.
What is API Testing?
API Testing is the process of verifying that an API functions correctly by validating requests, responses, status codes, business logic, security, performance, and error handling without involving the user interface.
Why is API Testing important?
API Testing is important because it: • Detects defects early • Validates business logic • Executes faster than UI testing • Supports CI/CD • Improves regression testing • Ensures reliable communication between systems
What is the difference between API Testing and UI Testing?
API Testing UI Testing Tests backend services Tests the user interface Faster Slower More stable Sensitive to UI changes Easier to automate Higher maintenance
What is REST?
REST (Representational State Transfer) is an architectural style for designing web services that communicate over HTTP using resources identified by URLs and standard HTTP methods.
What are the common HTTP methods?
• GET – Retrieve data • POST – Create data • PUT – Replace existing data • PATCH – Partially update data • DELETE – Remove data • HEAD – Retrieve headers only • OPTIONS – Retrieve supported operations
What is the difference between PUT and PATCH?
• PUT replaces the entire resource. • PATCH updates only specified fields of the resource.
What is a RESTful API?
A RESTful API follows REST principles such as stateless communication, resource-based URLs, standard HTTP methods, and meaningful HTTP status codes.
What are HTTP Status Codes?
HTTP Status Codes indicate the result of an API request. Examples: • 200 OK • 201 Created • 204 No Content • 400 Bad Request • 401 Unauthorized • 403 Forbidden • 404 Not Found • 409 Conflict • 429 Too Many Requests • 500 Internal Server Error
What is JSON?
JSON (JavaScript Object Notation) is a lightweight, text-based data format used to exchange structured information between clients and servers.
What is XML?
XML (eXtensible Markup Language) is a markup language used to represent structured data. Although JSON is more common today, XML is still used in many enterprise and legacy systems.
What is Statelessness?
Statelessness means each API request contains all the information required for processing, and the server does not store client session state between requests.
What is Idempotency?
An idempotent operation produces the same result when executed multiple times with the same input. Examples: • GET • PUT • DELETE (typically, though repeated deletes may return different status codes depending on the implementation)
What is Authentication?
Authentication verifies the identity of a user or client. Examples: • Basic Authentication • API Keys • Bearer Tokens • OAuth 2.0 • JWT
What is Authorization?
Authorization determines what an authenticated user is allowed to access or perform.
What is the difference between Authentication and Authorization?
Authentication Authorization Verifies identity Determines permissions Happens first Happens after authentication
What is OAuth 2.0?
OAuth 2.0 is an authorization framework that enables secure access to protected resources using access tokens without sharing user credentials with every request.
What is JWT?
JWT (JSON Web Token) is a compact, digitally signed token that securely carries claims between parties for authentication and authorization.
What is an Access Token?
An Access Token is a short-lived token used to access protected API resources.
What is a Refresh Token?
A Refresh Token is used to obtain a new Access Token after the current Access Token expires.
What is Schema Validation?
Schema Validation verifies that an API response matches the expected structure, required fields, and data types defined by the API contract.
What is API Chaining?
API Chaining is the process of using data returned by one API (such as an ID or token) as input for another API.
What are Dependent APIs?
Dependent APIs are APIs that require another API or its output before they can execute successfully.
What are Dynamic Responses?
Dynamic Responses contain values that change between executions, such as IDs, timestamps, UUIDs, or access tokens.
How do you validate an API response?
Validate: • Status code • Response body • Headers • Schema • Response time • Business rules • Data types
What is Positive API Testing?
Positive API Testing verifies that the API behaves correctly when valid input is provided.
What is Negative API Testing?
Negative API Testing verifies that the API handles invalid inputs, missing fields, unauthorized access, and error conditions correctly.
What is Boundary Value Testing?
Boundary Value Testing verifies values at the minimum, maximum, and edge limits of accepted input ranges.
What is API Contract Testing?
API Contract Testing verifies that requests and responses conform to the agreed API specification, such as an OpenAPI contract.
What is Mock API Testing?
Mock API Testing uses simulated API responses to test applications without depending on real backend services.
What is Rate Limiting?
Rate Limiting restricts the number of requests a client can send within a defined time period to protect API resources.
What is the difference between 401 and 403?
• 401 Unauthorized – Authentication is missing, invalid, or expired. • 403 Forbidden – Authentication succeeded, but the user does not have permission.
What is the difference between 200 and 201?
• 200 OK – Request completed successfully. • 201 Created – A new resource was successfully created.
What is API Automation?
API Automation is the use of scripts and frameworks to automatically execute API tests and validate expected results.
Which tools are commonly used for API Testing?
• Postman • REST Assured • Karate • ReadyAPI • JMeter • Playwright API Testing • Cypress API Testing
What is the role of Postman?
Postman is used to create, send, organize, automate, and validate API requests. It also supports collections, environments, scripting, and collaboration.
What is REST Assured?
REST Assured is a Java library used to automate REST API testing with a fluent syntax.
How do you debug API failures?
Check: • Status code • Request • Response • Authentication • Logs • Test data • Environment • Dependencies Then reproduce the issue using Postman or another API client if necessary.
What is CI/CD integration in API Testing?
CI/CD integration automatically executes API tests during build and deployment pipelines to provide fast feedback and prevent defective builds from progressing.
What are API Testing Best Practices?
• Write reusable tests • Avoid hardcoded values • Separate test data • Validate more than status codes • Use schema validation • Test positive and negative scenarios • Log requests and responses • Integrate with CI/CD
Frequently Asked Scenario-Based Questions
An API returns 500 Internal Server Error. What would you do? Answer: • Verify the request payload. • Check authentication. • Review logs and response details. • Reproduce the issue using Postman or cURL. • Check environment and dependencies. • If the issue is reproducible with a valid request, report it with supporting evidence.
How do you test a Login API?
Validate: • Valid credentials • Invalid credentials • Missing credentials • Expired tokens • Invalid tokens • Response time • Authentication headers • Security requirements
How do you test an Order API?
Verify: • Order creation • Mandatory fields • Invalid products • Duplicate requests • Authentication • Business rules • Payment integration • Order retrieval and deletion
How do you handle dynamic IDs?
Extract the ID from the API response, store it in a variable, validate its format and value, and reuse it in subsequent API requests instead of hardcoding it.
How do you reduce flaky API tests?
Use independent test data, avoid shared state, generate dynamic data where needed, synchronize correctly with asynchronous operations, isolate external dependencies when appropriate, and investigate intermittent failures instead of masking them with unnecessary retries.
Top Interview Tips
• Understand why an API behaves a certain way, not just how to call it. • Be comfortable reading HTTP requests and responses. • Know common status codes and when they apply. • Explain real-world examples whenever possible. • Distinguish clearly between authentication and authorization. • Understand API automation, debugging, and CI/CD concepts. • Discuss testing strategies, not just tools. • If you don't know an answer, explain how you would investigate it systematically.
Interview Summary
A strong API Testing candidate should be comfortable with: • REST architecture • HTTP methods and status codes • JSON and XML • Authentication and authorization • OAuth 2.0 and JWT • API security • Positive and negative testing • Contract and schema validation • Dynamic responses and API chaining • Automation with REST Assured, Karate, or Postman • CI/CD integration • Debugging API failures • Production monitoring • Real-world testing scenarios Mastering these concepts prepares you for the majority of API Testing interviews, from junior QA roles to senior API Automation Engineer positions.
Advanced Scenario-Based Interview Discussions
Senior interviews move beyond definitions and ask how you would design, prioritize, automate, diagnose, and operate API quality in a real delivery system. The following discussions show how to structure those answers around risk, evidence, tradeoffs, and maintainable engineering decisions.
Start with Risk and Purpose
Before writing a test, identify the risk it protects. A payment test may protect duplicate charging, authorization, amount calculation, or provider integration. Each risk needs different setup and assertions.
Automate stable, repeatable, high-value behavior first. Critical workflows, contracts, roles, boundaries, and known regressions usually provide stronger returns than large numbers of trivial success cases.
Do not automate solely because an endpoint exists. Low-risk, one-time, or rapidly changing behavior may be better explored manually until expectations stabilize.
Build a Modular Framework
Separate test intent from technical infrastructure. Tests describe scenarios and expected outcomes. Domain API clients communicate with endpoints. Builders create payloads. Configuration supplies environment values. Validators enforce shared contracts. Reporting captures evidence.
Modules should have clear responsibilities. An OrderClient should not also read spreadsheets and format reports. A data builder should not send HTTP requests. Clear ownership limits the effect of changes.
Modularity does not require a large number of layers. A small suite can use a few well-named classes. Add structure when it removes real duplication or supports operational needs.
Centralize Authentication
A dedicated authentication component should obtain, cache, refresh, and apply tokens or API keys. It can expose identities by role, scope, tenant, and environment.
Use least-privilege, short-lived credentials from approved secret stores. Never hardcode credentials or write them to logs.
Support intentional invalid, expired, missing, and insufficient credentials for negative testing. A framework that always injects an administrator token hides authorization defects.
Make Tests Independent
Each test should establish its own prerequisites and should be able to run alone, in any order, and repeatedly. Do not depend on another test creating or changing state.
If several steps represent one business workflow, keep them in one scenario and retain IDs in a test-scoped context. Do not split one workflow into ordered test methods.
Shared immutable reference data is acceptable. Shared mutable customers, orders, or accounts require safe allocation or isolation.
What Is API Contract Testing?
API Contract Testing verifies that an API implementation matches its defined contract and does not introduce breaking changes that could affect API consumers. It compares actual API behavior against the agreed specification or against contracts produced by consumers.
A simple definition is this: API Contract Testing ensures that an API always behaves according to its documented specification. If the contract says `GET /employees/{id}` returns an integer `id`, string `name`, and string `department`, the implementation should continue returning those fields with those types unless the contract is intentionally changed and versioned.
Contract testing can be provider-driven or consumer-driven. In provider-driven testing, the provider validates the API against a specification such as OpenAPI. In consumer-driven contract testing, consumers define the interactions they depend on, and the provider verifies those interactions before deployment. Both approaches aim to prevent accidental API incompatibility.
Contract testing is not the same as ordinary functional testing. Functional testing asks whether the API produces correct business behavior. Contract testing asks whether the API interface remains compatible. Both are necessary. An API can return correct business data but still violate the contract if field names, types, status codes, or structures change unexpectedly.
Breaking Changes
Breaking changes are changes that can cause existing consumers to fail. Examples include removing endpoints, renaming fields, changing data types, removing required fields, changing response structure, changing authentication requirements, removing status codes, changing URL paths, or changing error response format.
For example, changing this response:
{
"name": "John"
}
to this response can break existing clients:
{
"employeeName": "John"
}
Clients expecting `name` may show blank values, fail deserialization, or crash. Even if the new field name is more descriptive, it is still a breaking change unless introduced through a compatible strategy.
Breaking changes should be handled through API versioning, deprecation periods, migration documentation, or coordinated releases. Contract testing helps catch breaking changes before consumers discover them in production.
A Typical Pipeline
A pipeline commonly starts by checking out an immutable commit and resolving dependencies. It compiles code, runs static checks and unit tests, packages an artifact, scans dependencies and the artifact, and publishes the version.
The artifact is deployed to a test environment. Preflight checks confirm readiness and version identity. API smoke, contract, component, and integration tests execute according to scope. Reports and logs are published even if tests fail.
When all required gates pass, the same artifact may move to staging and production through approval or automatic deployment. Post-deployment checks verify successful release, and monitoring determines whether the new version remains healthy.
Quality Gates
A quality gate is a rule that determines whether the pipeline may proceed. Examples include successful build, all critical API tests passing, no incompatible contract changes, or no high-severity vulnerability.
Gates should be explicit and risk-based. A failed payment or authorization test should block release. An optional sandbox outage may follow a different policy but must remain visible.
A report communicates results; a gate acts on them. Publishing a red report while continuing deployment is not a meaningful control unless the failure is intentionally nonblocking.
Performance Metrics
Common performance metrics include response time, throughput, requests per second, transactions per second, latency, concurrent users, error rate, CPU usage, memory usage, disk I/O, network utilization, database connections, and queue depth. Each metric tells part of the story.
Response time is the total time taken by the API to process a request and return a response. Throughput measures how many requests or transactions the API successfully processes in a time period. Requests per second shows request handling capacity. Error rate shows the percentage of failed requests.
Resource utilization explains what the infrastructure is doing during the test. High CPU may indicate processing bottlenecks. High memory may indicate leaks or large object creation. High database connections may indicate connection pool pressure. High disk or network usage may reveal infrastructure limits.
Good performance analysis compares metrics together. High throughput with high error rate is not acceptable. Low response time with tiny load does not prove scalability. Acceptable average response time may hide poor 95th percentile response time. Performance quality is multidimensional.
Load Testing
Load Testing verifies API performance under expected user load. It answers whether the API can handle normal or planned traffic while meeting performance targets. For example, a test may simulate 500 users calling login, search, and checkout APIs with realistic pacing.
The expected result is that the API remains stable, response times stay within target, throughput meets expectations, and error rate remains low. Load testing is usually one of the first performance test types because it validates expected production usage.
A good load test uses realistic request distribution. If real users perform 60 percent search, 25 percent details, 10 percent cart updates, and 5 percent checkout, the test should reflect that mix. A load test that calls only one endpoint repeatedly may not represent production behavior.
Stress Testing
Stress Testing gradually increases load until the API reaches its breaking point. It helps determine maximum supported capacity and observe failure behavior. For example, load may increase from 500 users to 1000, 5000, and 10000 users.
The purpose is not only to make the system fail. The purpose is to learn how it fails. Does response time degrade gradually? Do errors increase? Does the server crash? Does the API recover after load drops? Are failures controlled or chaotic?
Stress testing helps capacity planning. If the system meets SLA up to 3000 users but fails beyond 4000, teams can plan scaling, optimization, or traffic controls before production demand reaches that level.
Spike Testing
Spike Testing introduces a sudden increase in traffic. For example, traffic may jump from 100 users to 5000 users immediately. This simulates flash sales, breaking news, marketing campaigns, payroll windows, exam result releases, ticket booking openings, or sudden mobile app activity.
The expected behavior is graceful degradation and recovery. The API may slow down temporarily, but it should not collapse, corrupt data, or remain degraded after the spike ends. Autoscaling, caching, rate limiting, queues, and circuit breakers often influence spike behavior.
Spike tests should measure both impact and recovery. How long does response time remain high? How many requests fail? Does the system recover automatically? Are queues drained correctly? These questions matter for production resilience.
Designing a Layered Token Test Strategy
A maintainable token test strategy assigns each risk to the cheapest layer that can prove it. Unit tests can validate claim construction, expiry calculations, scope evaluation, and policy functions without network calls. Authorization-server component tests can verify grant processing, credential checks, refresh rotation, revocation, and error contracts. Resource-server component tests can use controlled signed tokens or an identity simulator to exercise issuer, audience, lifetime, scope, role, and ownership decisions deterministically.
Contract tests then confirm that the authorization server and consuming APIs agree on key discovery, token type, required claims, scope names, error responses, and rotation behavior. Integration tests should use genuinely issued tokens to verify deployed configuration, trust relationships, networking, and policy. A smaller end-to-end suite can cover critical user journeys such as interactive login, consent, protected access, renewal, and logout. Keeping detailed permutations below the end-to-end layer provides broad coverage without repeatedly driving an expensive identity journey.
A coverage matrix helps prevent gaps. For every protected endpoint, record the accepted audience, token type, scopes or roles, resource ownership rule, tenant boundary, authentication strength, and expected response for denial. Map each rule to at least one allowed and one forbidden case. Also identify lifecycle coverage for issuance, expiry, refresh, rotation, revocation, password change, account disablement, and signing-key change. This matrix should be reviewed whenever an endpoint, role, client, identity provider, or authorization policy changes.
Test utilities must not become an unofficial security bypass. Helpers that mint arbitrary tokens are suitable for isolated component tests only when their trust boundary is explicit. Integration and end-to-end suites should obtain tokens through supported production-like flows. Distinguish simulated credentials in reports so a passing mocked test is never mistaken for proof that deployed identity integration works.
Ownership also matters. Identity teams may verify protocol compliance and issuance, while API teams verify resource authorization and business ownership. Security teams challenge abuse cases, and platform teams validate keys, secrets, availability, and monitoring. Shared contracts and a small cross-system suite connect these responsibilities. Without explicit ownership, every team may assume another team tested the most important boundary.
API Testing for Asynchronous APIs
Testing asynchronous APIs requires a workflow-based mindset. The first test step usually sends a request and validates that the provider accepted it. The response may be 202 Accepted and may contain a job id. The test should verify that the job id exists, has the right format, and can be used in later calls.
The next step is status validation. The test may poll a status endpoint until the job reaches Completed, Failed, Cancelled, or another final state. Polling should use a sensible interval and maximum wait time. Hardcoded long sleeps make tests slow and unreliable. A good async test waits until the expected condition appears or fails with clear diagnostics.
After completion, the test validates the final result. For report generation, it may verify that the download URL exists and the file is accessible. For file import, it may verify imported records and rejected rows. For email sending, it may verify that a message was queued or delivered in a test inbox. For webhook processing, it may verify that the receiving system recorded the event.
Negative testing is especially important for asynchronous APIs. What happens if the input is invalid? Does the API reject it immediately with 400, or accept it and fail the job later? What happens if background processing fails? Is the failure visible through status? Can the client retry? Does duplicate submission create duplicate side effects? These details must be defined and tested.
Classify the Failure Before Changing Code
Begin by classifying the signal. A 4xx response usually points toward request syntax, authentication, authorization, resource identity, business validation, or state conflict. A 5xx response suggests an unhandled application condition or failed dependency, although an invalid request can still expose a server defect. A timeout may originate in the client, gateway, service, database, network, or external provider. A test assertion failure can mean the product is wrong, the expectation is wrong, or the setup did not create the intended state.
Classification narrows investigation without becoming a conclusion. Record the observed status, latency, error contract, environment, build version, and whether the failure is reproducible. Avoid immediately adding waits, retries, or broader assertions. Those changes alter symptoms and can destroy the evidence needed to find the real cause.
SLIs, SLOs, SLAs, and Error Budgets
A service-level indicator is a measured signal such as successful-request ratio or p95 latency. A service-level objective defines the target for that indicator over a period. A service-level agreement is a business commitment that may include consequences. Keeping these terms separate prevents dashboards from confusing internal engineering goals with contractual promises.
An error budget represents the unreliability permitted by an SLO. If availability is targeted at 99.9 percent, the remaining fraction is the budget for failures. Burn-rate alerts identify when the service consumes that budget too quickly. This approach produces more meaningful alerts than reacting to every isolated error regardless of impact.
The Four Golden Signals
Latency measures how long requests take and should be viewed through percentiles, not only averages. Traffic measures demand such as requests per second, concurrent operations, payload volume, or messages processed. Errors include explicit failures, timeouts, malformed responses, and incorrect business outcomes. Saturation measures how close constrained resources are to their limits.
These signals explain different dimensions of health. Rising latency with high database connection usage suggests a different response from rising 401 errors after an identity deployment. Correlate signals by endpoint, version, region, instance, dependency, and customer impact while controlling label cardinality so the monitoring platform remains usable.
Alert Design and Alert Fatigue
Alerts should be actionable, urgent, and tied to user or objective impact. Route immediate pages for conditions requiring rapid human action and use tickets or dashboards for lower-priority trends. Include service, environment, affected operation, current value, threshold, duration, dashboard, runbook, and recent deployment information.
Avoid alerting on every single 500 response or static CPU threshold. Use sustained windows, ratios, baselines, multi-window burn rates, and dependency context. Regularly review noisy alerts, false positives, missed incidents, and alerts that required no action. An alert nobody trusts is operational debt.
Arrays, Ordering, and Changing Collection Sizes
Collections change as data changes, so fixed sizes and positions are safe only when the requirement guarantees them. Validate that the response is an array, each element follows the schema, required records are present, pagination metadata is consistent, and sorting follows the requested rule. Find an item by stable key instead of assuming it is always the first element.
When ordering is unspecified, compare sets or business keys rather than raw JSON strings. When ordering is specified, validate adjacent values and tie-breaking rules. Empty, single-item, maximum-page, duplicate, and multi-page cases deserve separate coverage.