What interviewers actually check in an API testing interview
API testing interviews are not a memory test on status codes. Interviewers are checking whether you understand the HTTP contract, can design meaningful test cases, and can automate them reliably. The six areas below come up again and again.
HTTP fundamentals
Request methods and idempotency, status code families, headers, query vs path parameters, request and response bodies, and JSON vs XML.
REST principles and API styles
REST vs SOAP vs GraphQL, resource naming, statelessness, PUT vs PATCH, and when a REST API breaks its own conventions.
Authentication and authorisation
Basic auth, API keys, Bearer/JWT tokens, OAuth 2.0 flows at a concept level, and how to test 401 vs 403 scenarios properly.
Postman and automation tooling
Collections, environments, variables, pre-request scripts, the Tests tab, Newman in CI, and chaining requests with extracted values.
REST Assured and Java
given/when/then syntax, Maven and TestNG setup, serialisation and deserialisation with POJOs, JSON path extraction and schema validation.
Test design and engineering habits
Positive, negative, boundary and auth test cases, idempotency checks, contract testing idea, mocking, rate limiting and API security basics.
API testing interview questions for freshers
These are the questions that come up first in API testing fresher interviews. They test whether your HTTP fundamentals are solid — answer with a short definition, then one line of why it matters.
Q01 What is an API, and how is API testing different from UI testing? +
An API (Application Programming Interface) is a contract that lets two software systems talk to each other. It defines the request format, the response format and the rules for using it.
API testing sends requests directly to the service and checks the response — status code, headers, body, schema and timing — without going through a browser. UI testing drives the actual user interface. API tests are faster, more stable and can catch bugs earlier because they bypass the front end.
Q02 What is REST, and how is it different from SOAP and GraphQL? +
| Feature | REST | SOAP | GraphQL |
|---|---|---|---|
| Protocol | HTTP | HTTP, SMTP, more | HTTP |
| Data format | JSON (usually), XML | XML only | JSON |
| Endpoint style | Multiple resource URLs | Single endpoint per service | Single endpoint, query-shaped |
| Strengths | Simple, cacheable, widely supported | Strict contract, built-in security standards | Client asks for exactly what it needs |
| Common use | Most public APIs | Legacy enterprise, banking | Modern front-end apps |
REST is an architectural style: stateless, resource-oriented, using standard HTTP methods. SOAP is a strict protocol with its own envelope and WSDL contract. GraphQL lets the client describe the exact shape of the response in one query.
Q03 What are the HTTP methods, and which ones are idempotent? +
| Method | Purpose | Idempotent? | Safe? |
|---|---|---|---|
| GET | Read a resource | Yes | Yes |
| POST | Create a resource | No | No |
| PUT | Replace a resource | Yes | No |
| PATCH | Partially update a resource | Not guaranteed | No |
| DELETE | Remove a resource | Yes | No |
| HEAD | Same as GET but headers only | Yes | Yes |
| OPTIONS | Describe allowed methods (CORS preflight) | Yes | Yes |
Idempotent means calling it once or many times leaves the server in the same state. That is why retrying a PUT or DELETE is safe, but retrying a POST may create duplicate records.
Q04 What is the difference between PUT and PATCH? +
PUT replaces the entire resource with the body you send. If you leave out a field, it may be set to null or removed, depending on the server.
PATCH applies a partial update. You send only the fields you want to change, and the server merges them with the existing resource.
// Existing user
{ "name": "Ravi", "email": "ravi@example.com", "age": 28 }
// PUT /users/1 — full replace (age will be lost or nulled)
{ "name": "Ravi Kumar", "email": "ravi@example.com" }
// PATCH /users/1 — partial update (age stays 28)
{ "name": "Ravi Kumar" }
Q05 What are the HTTP status code families, and which codes must you remember? +
Status codes are grouped by their first digit:
- 1xx — informational
- 2xx — success (200 OK, 201 Created, 204 No Content)
- 3xx — redirection (301 Moved Permanently, 302 Found, 304 Not Modified)
- 4xx — client error (400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 409 Conflict, 422 Unprocessable Entity, 429 Too Many Requests)
- 5xx — server error (500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable)
| Code | Meaning | Typical test trigger |
|---|---|---|
| 200 | OK | Successful GET |
| 201 | Created | Successful POST |
| 204 | No Content | Successful DELETE |
| 400 | Bad Request | Malformed JSON, missing required field |
| 401 | Unauthorized | Missing or invalid token |
| 403 | Forbidden | Valid token but no permission |
| 404 | Not Found | Resource ID does not exist |
| 409 | Conflict | Duplicate email on create |
| 422 | Unprocessable Entity | Valid JSON but semantic validation fails |
| 429 | Too Many Requests | Rate limit exceeded |
| 500 | Internal Server Error | Unhandled exception |
| 503 | Service Unavailable | Maintenance or overload |
Q06 What is the difference between 401 Unauthorized and 403 Forbidden? +
401 Unauthorized means the request lacks valid authentication — no token, expired token, wrong credentials. The server does not know who you are.
403 Forbidden means the server knows who you are but you do not have permission to access that resource. Re-authenticating will not help.
Q07 What are headers in an HTTP request and response? +
Headers carry metadata about the request or response. They do not hold the main data — that is in the body — but they control how it is processed.
Common request headers:
Content-Type— the format of the request body (application/json, application/xml)Accept— the format the client wants backAuthorization— the credentials (Bearer token, Basic base64)User-Agent— identifies the client
Common response headers:
Content-Type— the format of the response bodyCache-Control— caching rulesLocation— where a newly created resource lives (with 201)X-RateLimit-Remaining— how many API calls are left in the window
Q08 What is the difference between query parameters and path parameters? +
Path parameters are part of the URL path and
usually identify a specific resource:
/users/42.
Query parameters come after a question mark and
usually filter, sort or paginate:
/users?role=admin&page=2.
| Type | Example | Use for |
|---|---|---|
| Path | /users/42 | Identifying a specific resource |
| Query | /users?role=admin | Filtering, sorting, pagination |
Q09 What is JSON, and how is it different from XML in API testing? +
JSON is a lightweight text format using key-value pairs and arrays. It is easy to read and parse, and it is the default for most modern REST APIs.
XML is more verbose, uses tags and attributes, and supports schemas (XSD) and namespaces. It is still common in SOAP and older enterprise systems.
// JSON
{ "id": 1, "name": "Ravi", "role": "admin" }
<!-- XML -->
<user>
<id>1</id>
<name>Ravi</name>
<role>admin</role>
</user>
In Postman and REST Assured, JSON is parsed with JSON path expressions; XML is parsed with XPath.
Q10 What is the difference between authentication and authorisation? +
Authentication answers "who are you?" — it verifies identity through credentials (password, API key, token).
Authorisation answers "what are you allowed to do?" — it checks permissions after identity is confirmed.
In testing: a missing token should give 401; a valid token without the required role should give 403.
Q11 What are the common authentication methods used in REST APIs? +
| Method | How it works | Where it is used |
|---|---|---|
| Basic Auth | Base64 of username:password in the Authorization header | Internal tools, legacy APIs (only over HTTPS) |
| API Key | A static key sent in a header or query parameter | Public APIs, third-party services |
| Bearer / JWT | A signed token in the Authorization header; carries claims | Modern SPAs, mobile apps, microservices |
| OAuth 2.0 | Delegated access with access and refresh tokens | Login with Google, third-party integrations |
For testing, the key scenarios are: valid credentials, missing credentials, expired credentials and insufficient permissions.
Q12 What is a JSON schema, and why validate it? +
A JSON schema describes the expected structure of a JSON response — which fields exist, their types, which are required, and any constraints like minimum length or allowed values.
Validating against a schema catches contract breaks
that simple field assertions miss. If the API suddenly
returns age as a string instead of a
number, a schema test fails immediately even though the
field is still present.
{
"type": "object",
"required": ["id", "name", "email"],
"properties": {
"id": { "type": "integer" },
"name": { "type": "string" },
"email": { "type": "string", "format": "email" }
}
}
Q13 What is Postman, and what are collections and environments? +
Postman is a GUI tool for sending HTTP requests and inspecting responses. It is the most common tool for manual API testing and for building quick automation suites.
- Collection — a folder of related requests, usually one collection per API or feature.
- Environment — a set of key-value variables (base URL, token, user ID) that can be switched without editing each request.
- Variables — placeholders like
{{baseUrl}}that get replaced at request time. - Tests tab — JavaScript assertions that run after the response is received.
- Pre-request script — JavaScript that runs before the request, useful for generating tokens or timestamps.
Q14 What is Newman, and how is it used in CI? +
Newman is the command-line runner for Postman collections. You export a collection and environment, then run them from a terminal or a CI job.
newman run UserApi.postman_collection.json \
-e staging.postman_environment.json \
--reporters cli,htmlextra
In CI, a Newman step fails the build if any assertion fails, so API regressions are caught before deployment.
Q15 What is REST Assured, and why do teams use it instead of Postman? +
REST Assured is a Java library for testing and
validating REST APIs. It gives you a fluent
given() / when() / then() syntax.
Teams use it over Postman when they need tests inside the same codebase, want to share POJOs and utilities with developers, need complex data setup, or want Maven/TestNG/Jenkins integration with fine-grained reporting.
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
given()
.baseUri("https://api.example.com")
.when()
.get("/users/1")
.then()
.statusCode(200)
.body("name", notNullValue());
Tests passed · status 200 · body contains name
Intermediate API testing interview questions
These questions come up for candidates with 2–4 years of experience. They test whether you understand the why behind API design and can build reliable automation.
Q16 How do you set up REST Assured in a Maven project? +
Add the dependency to your pom.xml. You
usually also add TestNG and a JSON schema validator.
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.4.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.9.0</version>
<scope>test</scope>
</dependency>
In a base test class, set
RestAssured.baseURI and any common
headers. Then write tests with
given() / when() / then().
Q17 How do you send a POST request with a JSON body in REST Assured? +
You can send the body as a raw string, a Map, or a POJO. POJOs are the cleanest because they are type-safe and reusable.
Map<String, Object> body = new HashMap<>();
body.put("name", "Ravi");
body.put("email", "ravi@example.com");
body.put("role", "admin");
given()
.baseUri("https://api.example.com")
.contentType("application/json")
.body(body)
.when()
.post("/users")
.then()
.statusCode(201)
.body("name", equalTo("Ravi"));
Tests passed · status 201 Created
Q18 How do you extract a value from a JSON response and use it in the next request? +
This is the classic chaining pattern: create a resource, grab its ID from the response, then use that ID in the next call.
// Step 1: create the user and extract the ID
int userId = given()
.baseUri("https://api.example.com")
.contentType("application/json")
.body("{\"name\":\"Ravi\",\"email\":\"ravi@example.com\"}")
.when()
.post("/users")
.then()
.statusCode(201)
.extract().path("id");
// Step 2: use the ID in a GET
given()
.baseUri("https://api.example.com")
.when()
.get("/users/" + userId)
.then()
.statusCode(200)
.body("name", equalTo("Ravi"));
Tests passed · status 200 OK
Q19 How do you validate a JSON schema in REST Assured? +
Add the json-schema-validator dependency,
store your schema in src/test/resources,
and use matchesJsonSchemaInClasspath.
import static io.restassured.module.jsv.JsonSchemaValidator.*;
given()
.baseUri("https://api.example.com")
.when()
.get("/users/1")
.then()
.statusCode(200)
.body(matchesJsonSchemaInClasspath("user-schema.json"));
Tests passed · response matches schema
Q20 What is serialisation and deserialisation in REST Assured? +
Serialisation converts a Java object into JSON for the request body. Deserialisation converts a JSON response into a Java object.
REST Assured uses Jackson or Gson under the hood. When
you pass a POJO to body(), it serialises
automatically. When you call
as(MyPojo.class), it deserialises.
public class User {
public String name;
public String email;
}
// serialise: POJO → JSON
User u = new User();
u.name = "Ravi"; u.email = "ravi@example.com";
given().contentType("application/json").body(u)
.when().post("/users")
.then().statusCode(201);
// deserialise: JSON → POJO
User created = get("/users/1").as(User.class);
Q21 How do you pass authentication headers in REST Assured? +
REST Assured has built-in helpers for Basic and OAuth 2.0, and you can set any custom header directly.
// Basic auth
given().auth().basic("username", "password")
.when().get("/protected")
.then().statusCode(200);
// Bearer token
given().header("Authorization", "Bearer " + token)
.when().get("/profile")
.then().statusCode(200);
// API key in header
given().header("x-api-key", apiKey)
.when().get("/data")
.then().statusCode(200);
Q22 How do you chain requests in Postman using environment variables? +
In the first request's Tests tab, extract the value
and save it as an environment variable. The next
request references it with {{variable}}.
const res = pm.response.json();
pm.environment.set("userId", res.id);
pm.test("User created", () => {
pm.response.to.have.status(201);
});
GET https://api.example.com/users/{{userId}}
Q23 What is a pre-request script in Postman, and when do you use it? +
A pre-request script runs before the request is sent. It is used to generate dynamic values such as a timestamp, a random ID, or a signed token.
// generate a unique email for each run
const unique = Date.now();
pm.environment.set("email", `user${unique}@example.com`);
This avoids 409 Conflict errors when the same test runs repeatedly against a persistent environment.
Q24 What is contract testing, and how is it different from functional API testing? +
Functional API testing checks that the API behaves correctly for a given input — status, body, business rules.
Contract testing checks that two services agree on the shape of their interaction — the request and response structure — without needing both services running. Tools like Pact create a contract from the consumer side and verify it against the provider.
Contract tests catch breaking changes early in microservice environments, before integration tests run.
Q25 What is API mocking, and when do you use it? +
API mocking means standing up a fake server that returns predefined responses. You use it when the real API is not ready, is unreliable, is expensive to call, or when you need to simulate error conditions that are hard to trigger on the real service.
Postman has built-in mock servers; WireMock and MockServer are common in Java projects. Mocks are for development and testing only — you still need integration tests against the real service.
Q26 How do you test rate limiting on an API? +
Rate limiting returns 429 Too Many Requests once a client exceeds the allowed number of calls in a window. To test it:
- Send requests in a tight loop until the API returns 429.
- Assert the response includes a
Retry-Afterheader and/orX-RateLimit-*headers. - Wait for the window to reset and verify normal calls succeed again.
- Confirm that different API keys or users have independent limits.
Run this against staging, not production, and with an explicit approval from the API owner.
Q27 How do you test pagination in a REST API? +
Pagination usually comes in one of two styles:
- Offset/limit —
/users?page=2&size=20. - Cursor-based —
/users?after=abc123.
What to test:
- Page 1 returns the correct number of items.
- Consecutive pages do not repeat or skip records.
- The total count or next-cursor matches the actual data.
- Requesting a page beyond the last returns an empty list or 404, as documented.
- Invalid page or size values are handled gracefully (400 or default).
Q28 What are the OWASP API security risks, at a concept level? +
The OWASP API Security Top 10 lists the most common API-specific risks. The ones that matter most in day-to-day testing are:
- Broken object level authorisation — a user can access another user's record by changing an ID. Test this explicitly.
- Broken authentication — weak tokens, no expiry, missing token validation.
- Excessive data exposure — the API returns more fields than the client needs, leaking sensitive data.
- Lack of resources and rate limiting — no protection against brute force or abuse.
- Mass assignment — a client can set fields it should not, like
role: "admin".
As a tester, the practical checks are: try IDOR by swapping IDs, send a request without a token, send a request with an expired token, and attempt to set restricted fields.
Q29 What is the difference between API testing and integration testing? +
API testing focuses on one service: does this endpoint return the right status, headers and body for valid and invalid input?
Integration testing checks that multiple services or components work together — service A calls service B, the database is updated, the message is queued. It covers the seams between systems, not the internals of one.
In practice, API tests are usually faster and run earlier; integration tests are slower and catch communication and data-flow issues.
Q30 How do you handle authentication tokens that expire during a test run? +
Do not hard-code tokens. Fetch a fresh token at the start of the run and reuse it. If the token can expire mid-run, add a refresh step.
public class AuthHelper {
private static String token;
public static String getToken() {
if (token == null) {
token = given()
.contentType("application/json")
.body("{\"username\":\"tester\",\"password\":\"secret\"}")
.when()
.post("/auth/login")
.then()
.statusCode(200)
.extract().path("token");
}
return token;
}
}
API testing interview questions for experienced professionals
These questions come up for candidates with 5+ years of experience or for anyone interviewing at a product company. They expect you to reason about framework design, not just write a single test.
Q31 How would you design an API automation framework from scratch? +
Layer 1 — Base setup: a base test class that sets base URI, common headers and authentication once.
Layer 2 — API clients: one class per resource (UserApiClient, OrderApiClient)
with methods like createUser(), getUser(). Tests call
these methods instead of writing raw HTTP.
Layer 3 — Models: POJOs for requests and responses, generated or hand-written. Use Jackson or Gson.
Layer 4 — Utilities: helpers for token retrieval, random data generation, config reading from properties files, and DB assertions if needed.
Layer 5 — Test data: externalise test data to JSON or CSV files so tests are not tied to hard-coded values.
Layer 6 — Tests: TestNG or JUnit tests that call the API clients and assert status, body and schema.
Layer 7 — Reporting and CI: Allure or Extent reports, and a Jenkins or GitHub Actions pipeline that runs the suite on every commit.
Keep configuration in one place, keep tests independent, and always clean up test data.
Q32 How do you test an API that depends on another API? +
Separate the concerns:
- Contract tests — verify that the upstream API returns the shape your service expects. Run these independently so you know quickly if the upstream changed.
- Stubbed tests — mock the upstream service with WireMock and test your API's behaviour for success, error and timeout responses. This is fast and deterministic.
- End-to-end tests — run a smaller set against the real upstream in a staging environment. These are slower but catch real integration issues.
Do not make every test depend on a live third-party service — one outage will fail your whole suite.
Q33 How do you test an asynchronous or event-driven API? +
Async APIs return 202 Accepted and a job ID, then notify completion through a webhook, a message queue or a status endpoint you poll.
- Polling pattern — call the status endpoint with the job ID until it returns completed or failed. Assert on the final payload.
- Webhook pattern — stand up a test listener, trigger the job, and assert the webhook payload matches the expected schema and content.
- Queue pattern — subscribe to the message broker in the test and assert the message is published with the right body.
Always include a timeout. An async test that waits forever will hang the CI pipeline.
Q34 How do you approach performance testing for an API? +
Start with a clear goal: how many requests per second at what response time and error rate?
- Baseline — run a single-user test and record response time for each endpoint.
- Load test — ramp up to expected peak traffic and check that p95 latency and error rate stay within limits.
- Stress test — push beyond peak until the system breaks, and note where it breaks.
- Soak test — run at moderate load for hours to catch memory leaks and connection pool exhaustion.
JMeter and k6 are the common tools. Always test in an environment that matches production, and never run load tests against production without explicit approval.
Q35 How do you test idempotency of an API? +
For PUT and DELETE, idempotency means calling the same request twice should leave the server in the same state.
- Send the request once and record the response and the resulting server state.
- Send the exact same request again.
- Assert that the final server state is identical — not that the response is identical. For DELETE, the second call may return 404 or 204; both are acceptable if the resource is gone.
For POST, idempotency is not required by the spec,
but many APIs support an
Idempotency-Key header. Test that two
POSTs with the same key create only one record.
Q36 How do you handle test data setup and teardown for API tests? +
Each test should create the data it needs and clean up after itself, so tests can run in any order and in parallel.
- Create via API — prefer creating test data through the API itself, so you test the real path.
- Unique identifiers — generate unique emails, usernames or IDs per run to avoid conflicts.
- Teardown — delete the created resources in an
@AfterMethodor equivalent, even if the test failed. - Database reset — for integration tests, a clean database snapshot restored before the suite is the most reliable approach.
- No shared state — never let one test depend on data created by another. That creates order-dependent flakiness.
Q37 What is the difference between a 400 and a 422 status code, and when would you use each? +
400 Bad Request means the request itself is malformed — invalid JSON syntax, missing required header, wrong content type. The server cannot even parse the request.
422 Unprocessable Entity means the request is syntactically valid but fails semantic validation — for example, a date of birth in the future, an age below the allowed minimum, or a start date after the end date.
Not all APIs use 422. Some teams return 400 for both. What matters in testing is consistency: check what the API documents and assert accordingly.
Q38 How do you test file upload and download APIs? +
File uploads use multipart/form-data.
In REST Assured:
given()
.multiPart("file", new File("src/test/resources/sample.pdf"))
.when()
.post("/upload")
.then()
.statusCode(200)
.body("fileName", equalTo("sample.pdf"));
What to test:
- Valid file type and size upload succeeds.
- Unsupported file type is rejected (415 or 400).
- File exceeding the size limit is rejected (413).
- Download returns the correct content type, content length and file bytes.
- Download of a file you do not own returns 403 or 404, not the file.
Q39 How do you measure API test coverage? +
API test coverage is not a single number. Track these dimensions:
- Endpoint coverage — how many of the documented endpoints have at least one automated test.
- Method coverage — for each endpoint, are all supported methods tested?
- Status code coverage — for each endpoint, are the success and error codes covered (200, 201, 400, 401, 403, 404, 409)?
- Parameter coverage — are required, optional and boundary values for each parameter tested?
- Auth coverage — is each endpoint tested with valid, missing, expired and insufficient-permission credentials?
A coverage matrix in a spreadsheet or a dashboard is more useful than a single percentage.
Q40 How do you keep API tests stable when the API evolves? +
Test maintenance is the biggest cost in API automation. Practical habits:
- Assert on the contract, not on every field — validate the schema and the key fields that matter, not the entire response body.
- Centralise endpoints and payloads — if the URL or payload shape changes, you edit one place.
- Use POJOs instead of raw strings — a compile error is easier to fix than a runtime 400.
- Version your tests with the API — run the old suite against the old version until it is retired.
- Fail fast on contract changes — a schema test that fails immediately tells you exactly what changed.
Q41 What is the difference between API testing and API monitoring? +
API testing runs before release, in CI or on a staging environment. It verifies correctness for a wide range of inputs and edge cases. It is comprehensive but not continuous.
API monitoring runs continuously in production. It checks that key endpoints are reachable, returning the right status and within expected response time. It is shallow but always on.
You need both: tests catch bugs before users see them; monitoring catches outages and regressions after deployment.
Q42 How do you test API versioning? +
Common versioning styles: URL path
(/v1/users), query parameter
(/users?version=1), custom header
(Accept: application/vnd.api+json;version=1).
What to test:
- Each supported version still works for its documented behaviour.
- Deprecated versions return a warning header (Deprecation, Sunset) if documented.
- Removed versions return 404 or 410 Gone, not a silent fallback.
- A request with an unsupported version returns a clear error, not the latest version.
- Behaviour is consistent — the same request to the same version gives the same response shape.
Scenario-based API testing interview questions
These are the questions an interviewer asks when they want to see how you think under a realistic problem, not just how well you recall definitions. Answer with a step-by-step approach.
S01 A POST endpoint sometimes returns 500 on valid input. How do you debug it? +
Step 1 — Check whether the failure is consistent or intermittent. If intermittent, it may be a race condition, a downstream timeout or a resource limit.
Step 2 — Look at the server logs for the exact request that failed. The stack trace usually points to the cause — a null pointer, a constraint violation, a connection pool exhaustion.
Step 3 — Test with minimal valid payload, then add fields one at a time. This isolates which field or combination triggers the failure.
Step 4 — Check for database constraints. A unique index on email will throw a 500 if the API does not catch the duplicate key exception and return 409 instead.
Step 5 — Confirm whether the same request succeeds on a freshly restarted service. If it does, you are likely leaking connections or memory.
S02 An API returns 200 with an error message in the body instead of a proper 4xx code. What do you do? +
Step 1 — Document the behaviour with evidence: the request, the 200 response, and the error payload. This is a design issue, not just a bug.
Step 2 — Raise it with the API owner. The correct behaviour is a 4xx status so that clients, monitoring and gateways can react properly.
Step 3 — In your tests, assert the current behaviour (200 + error body) so the suite passes, but mark it as a known issue and link it to the ticket.
Step 4 — Once fixed, update the tests to assert the new status code and remove the known-issue flag.
Step 5 — Add this to your API review checklist so new endpoints do not repeat the mistake.
S03 Your API test suite passes locally but fails in CI. How do you investigate? +
Step 1 — Compare environments. CI may point to a different base URL, use a different database, or have different environment variables.
Step 2 — Check for timing issues. CI machines are often slower. Increase timeouts and add explicit waits for async operations.
Step 3 — Check for test pollution. If tests share state and CI runs them in parallel, one test may be deleting data another needs.
Step 4 — Check for hard-coded IDs or emails. Locally these may exist; in CI they may not.
Step 5 — Reproduce the CI run locally with the same environment variables and the same parallel settings. The failure will usually appear.
S04 You need to test an API that has no documentation. How do you start? +
Step 1 — If there is an OpenAPI/Swagger spec at a standard path
(/swagger.json, /openapi.json), import it into Postman.
That gives you most of the contract.
Step 2 — If not, observe the UI. Open browser DevTools, use the application, and capture every network request. That reveals the endpoints, headers and payloads the front end uses.
Step 3 — Ask the developer for a sample collection or a few example requests. Most developers have a Postman collection they use themselves.
Step 4 — Probe safely: send a request without a token to see what auth is enforced; send a malformed body to see what validation exists.
Step 5 — Document what you discover and share it. You will be creating the documentation the team was missing.
S05 An API returns sensitive data of other users when you change the ID in the URL. How do you confirm and report it? +
Step 1 — Reproduce it carefully. Log in as User A, note your own ID, then request User B's ID. Record the exact request and response.
Step 2 — Confirm it is not a false positive. Make sure User B's data is genuinely not visible to User A anywhere else, and that the token used belongs to User A only.
Step 3 — Stop testing once confirmed. Do not enumerate IDs or download data. This is a broken object level authorisation (BOLA/IDOR) issue — a serious vulnerability.
Step 4 — Report through the security channel, not a public ticket. Include the request, response, timestamps and the account used.
Step 5 — After the fix, add an automated test that asserts 403 or 404 when one user requests another user's resource.
S06 Your team wants to test an API that is not built yet. How do you prepare? +
Step 1 — Work from the API contract. If there is an OpenAPI spec or a design document, review it and write test cases against the expected behaviour.
Step 2 — Set up a mock server from the spec. Postman and WireMock can both generate mocks from an OpenAPI file. Your tests can be written and run against the mock before the real API exists.
Step 3 — Identify edge cases early — boundary values, invalid types, missing required fields — and share them with the developer. This often improves the implementation before it is written.
Step 4 — Prepare the test data and the environment. When the real API is ready, you only need to switch the base URL.
Step 5 — Once the API is live, run the same suite against it and compare with the mock behaviour.
S07 An API works on HTTP but fails on HTTPS. What do you check? +
Step 1 — Check the TLS certificate. Expired, self-signed or wrong-host certificates cause the client to reject the connection.
Step 2 — Check for mixed content. If the API returns URLs pointing to HTTP resources, browsers and some clients will block them.
Step 3 — Check redirects. The HTTP endpoint may redirect to HTTPS, and the client may not follow the redirect or may drop the Authorization header on redirect.
Step 4 — Check TLS version and cipher support. Older clients may not support the TLS version the server requires.
Step 5 — Use curl -v or Postman's console to see the exact TLS
handshake failure. That usually identifies the cause immediately.
S08 A DELETE endpoint returns 200 with a success message but the resource still exists. How do you report it? +
Step 1 — Reproduce it cleanly: create a resource, delete it, then immediately GET it. If GET returns the resource, the delete did not work.
Step 2 — Confirm by querying the database or the admin API directly, if available. This rules out a caching issue on GET.
Step 3 — Check whether the delete is soft — some APIs mark a record as deleted but keep the row. In that case the GET should return 404; if it still returns 200, the filter is missing.
Step 4 — Write the report with: exact steps, the create response, the delete response, the GET response, and the environment. Include timestamps.
Step 5 — Add a regression test that deletes a resource and asserts the follow-up GET returns 404.
S09 You need to run the same API test suite against dev, staging and production. How do you structure it? +
Step 1 — Externalise the base URL, credentials and any environment-specific values into property files or environment variables. Never hard-code them.
Step 2 — Use a Maven profile or a system property to select the environment at run time.
Step 3 — Tag tests that should not run against production — anything that creates or deletes data. Run only read-only smoke tests in production.
Step 4 — Use separate test accounts per environment, and never point production tests at real customer data.
Step 5 — Keep the suite fast in production. A small set of critical-path checks is better than the full regression suite running against live data.
S10 Your API test is flaky — it passes 8 out of 10 runs. How do you fix it? +
Step 1 — Add logging. Capture the full request and response for each run so you can compare the failing run with a passing one.
Step 2 — Look for time dependence. Tests that depend on today's date, a timestamp within a second, or a token that expires quickly will flake.
Step 3 — Look for shared state. If two tests use the same email or ID, one may run before the other cleans up.
Step 4 — Look for async gaps. If the API is eventually consistent, a GET immediately after a POST may return stale data. Add a retry with backoff, or poll a status endpoint.
Step 5 — Once fixed, run the test 20 times in a row. If it is still flaky, the cause is in the environment or the API, not the test.
Hands-on round — Postman, REST Assured and test cases
This section gives you the exact code that interviewers ask for in the practical round. Write each snippet by hand before your interview — reading code is not the same as writing it.
P01 Postman — assert status code and response time +
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
pm.test("Response time is under 800ms", function () {
pm.expect(pm.response.responseTime).to.be.below(800);
});
PASS Status code is 200 PASS Response time is under 800ms
P02 Postman — validate JSON body fields +
Sample response:
{
"id": 1,
"name": "Leanne Graham",
"email": "leanne@example.com",
"role": "admin"
}
const body = pm.response.json();
pm.test("Name is Leanne Graham", () => {
pm.expect(body.name).to.eql("Leanne Graham");
});
pm.test("Email is valid format", () => {
pm.expect(body.email).to.match(/^[^@\s]+@[^@\s]+\.[^@\s]+$/);
});
pm.test("Role is admin", () => {
pm.expect(body.role).to.be.oneOf(["admin", "user"]);
});
PASS Name is Leanne Graham PASS Email is valid format PASS Role is admin
P03 Postman — validate JSON schema +
const schema = {
type: "object",
required: ["id", "name", "email"],
properties: {
id: { type: "integer" },
name: { type: "string" },
email: { type: "string", format: "email" }
}
};
pm.test("Response matches JSON schema", () => {
pm.response.to.have.jsonSchema(schema);
});
PASS Response matches JSON schema
P04 Postman — set an environment variable from the response +
const res = pm.response.json();
pm.test("User created", () => {
pm.response.to.have.status(201);
});
// save the new user ID for the next request
pm.environment.set("userId", res.id);
// save the auth token from the login response
if (res.token) {
pm.environment.set("authToken", res.token);
}
The next request uses
{{userId}} in the URL and
{{authToken}} in the Authorization
header.
P05 Postman — chain requests and assert the created resource +
Request 1 — POST /users (Tests tab):
const created = pm.response.json();
pm.environment.set("newUserId", created.id);
pm.test("Created with correct name", () => {
pm.expect(created.name).to.eql("Ravi");
});
Request 2 — GET /users/{{newUserId}} (Tests tab):
const fetched = pm.response.json();
pm.test("Fetched user matches created user", () => {
pm.response.to.have.status(200);
pm.expect(fetched.id).to.eql(pm.environment.get("newUserId"));
pm.expect(fetched.name).to.eql("Ravi");
});
R01 REST Assured — GET with given/when/then +
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class GetUserTest {
public static void main(String[] args) {
given()
.baseUri("https://api.example.com")
.header("Accept", "application/json")
.when()
.get("/users/1")
.then()
.statusCode(200)
.body("id", equalTo(1))
.body("name", notNullValue());
}
}
Tests passed · status 200 · id = 1 · name present
R02 REST Assured — POST with a JSON body +
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class CreateUserTest {
public static void main(String[] args) {
String body = """
{
"name": "Ravi",
"email": "ravi@example.com",
"role": "admin"
}
""";
given()
.baseUri("https://api.example.com")
.contentType("application/json")
.body(body)
.when()
.post("/users")
.then()
.statusCode(201)
.body("name", equalTo("Ravi"))
.body("id", notNullValue());
}
}
Tests passed · status 201 Created · id returned
Note: Java 15+ text blocks (""") make multi-line
JSON readable. For Java 8, use a concatenated string or a POJO.
R03 REST Assured — auth header and JSON path extraction +
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class AuthAndExtractTest {
public static void main(String[] args) {
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...";
// GET with Bearer token and extract a field
String userName =
given()
.baseUri("https://api.example.com")
.header("Authorization", "Bearer " + token)
.when()
.get("/profile")
.then()
.statusCode(200)
.extract().path("user.name");
System.out.println("Extracted name: " + userName);
}
}
Extracted name: Ravi Kumar
R04 REST Assured — schema validation +
Store user-schema.json in
src/test/resources and use
matchesJsonSchemaInClasspath.
import static io.restassured.RestAssured.*;
import static io.restassured.module.jsv.JsonSchemaValidator.*;
public class SchemaTest {
public static void main(String[] args) {
given()
.baseUri("https://api.example.com")
.when()
.get("/users/1")
.then()
.statusCode(200)
.body(matchesJsonSchemaInClasspath("user-schema.json"));
}
}
Tests passed · response matches user-schema.json
R05 REST Assured — deserialise response into a POJO +
import static io.restassured.RestAssured.*;
public class User {
public int id;
public String name;
public String email;
}
public class PojoTest {
public static void main(String[] args) {
User user =
given()
.baseUri("https://api.example.com")
.when()
.get("/users/1")
.then()
.statusCode(200)
.extract().as(User.class);
System.out.println(user.name + " / " + user.email);
}
}
Leanne Graham / leanne@example.com
| # | Category | Scenario | Input | Expected result |
|---|---|---|---|---|
| TC-01 | Positive | Create user with all valid fields | name, email, role = valid | 201 Created · response contains id, name, email |
| TC-02 | Positive | Create user with only required fields | name, email | 201 Created · role defaults if documented |
| TC-03 | Negative | Missing required field (email) | name only | 400 Bad Request · error mentions email |
| TC-04 | Negative | Invalid email format | email = "not-an-email" | 400 Bad Request · validation error |
| TC-05 | Negative | Duplicate email | email already exists | 409 Conflict · duplicate error |
| TC-06 | Boundary | Name at minimum length | name = 1 character | 201 Created if min length is 1, else 400 |
| TC-07 | Boundary | Name at maximum length | name = max allowed characters | 201 Created |
| TC-08 | Boundary | Name one character over maximum | name = max + 1 | 400 Bad Request |
| TC-09 | Auth | No Authorization header | valid body, no token | 401 Unauthorized |
| TC-10 | Auth | Expired token | valid body, expired token | 401 Unauthorized |
| TC-11 | Auth | Valid token, insufficient role | user token, admin-only endpoint | 403 Forbidden |
| TC-12 | Idempotency | Same request with same Idempotency-Key | two identical POSTs with key K | 201 first time · 200 or 409 second time · only one record created |
| TC-13 | Content | Wrong Content-Type | text/plain body | 415 Unsupported Media Type |
| TC-14 | Content | Malformed JSON | {"name": } | 400 Bad Request · parse error |
| TC-15 | Security | Mass assignment attempt | extra field "isAdmin": true | Field ignored or 400 · user is not admin |
Quick-revision cheat table
Fifteen one-line definitions and reminders to skim on the morning of your interview.
| Topic | One-line reminder |
|---|---|
| API | A contract between two systems defining request, response and rules. |
| REST | Stateless, resource-oriented architecture using standard HTTP methods. |
| Idempotent methods | GET, PUT, DELETE, HEAD, OPTIONS — safe to retry. |
| PUT vs PATCH | PUT replaces the whole resource; PATCH updates only the fields sent. |
| 401 vs 403 | 401 = not authenticated; 403 = authenticated but not permitted. |
| 400 vs 422 | 400 = malformed request; 422 = valid syntax but semantic validation failed. |
| 429 | Rate limit exceeded; check Retry-After and X-RateLimit-* headers. |
| Path vs query param | Path identifies a resource; query filters, sorts or paginates. |
| JSON schema | Describes expected structure; validates types and required fields. |
| Postman collection | Folder of related requests; environment holds variables. |
| Pre-request script | Runs before the request; use for tokens, timestamps, random data. |
| Tests tab | Runs after the response; use pm.test and pm.expect for assertions. |
| Newman | CLI runner for Postman collections; use in CI pipelines. |
| REST Assured | Java library with given/when/then syntax for API tests. |
| Serialisation | Java object → JSON for the request; deserialisation is the reverse. |
| Contract testing | Verifies two services agree on request/response shape without both running. |
| API mocking | Fake server with predefined responses; used when the real API is unavailable. |
| IDOR / BOLA | Accessing another user's data by changing an ID; test by swapping IDs. |
| Performance testing | Baseline, load, stress, soak — measure p95 latency and error rate. |
| API monitoring | Continuous shallow checks in production; complements pre-release testing. |
How to prepare for an API testing interview in 7 days
If your interview is next week, follow this plan. Each day has a single focus and a practice task — do not just read, write code.
| Day | Focus | Practice task |
|---|---|---|
| Day 1 | HTTP fundamentals | Answer Q1–Q8 out loud. Write a table of methods, idempotency and common status codes from memory. |
| Day 2 | Authentication and security | Answer Q10–Q11 and Q28. Set up Postman with Basic auth, API key and Bearer token requests. Test 401 and 403 scenarios. |
| Day 3 | Postman basics | Create a collection with a POST and a GET. Chain them using environment variables. Write 3 tests in the Tests tab. |
| Day 4 | Postman advanced | Add a pre-request script, validate JSON schema, and run the collection with Newman from the command line. |
| Day 5 | REST Assured setup | Create a Maven project, add the dependency, and write the GET and POST snippets from R01 and R02. Run them. |
| Day 6 | REST Assured advanced | Write the auth, extraction, schema and POJO snippets from R03, R04, R05. Run all of them. |
| Day 7 | Test design and mock interview | Write the Create User test-case table from memory. Answer one scenario question per level out loud. |
Common mistakes candidates make
Only testing the happy path
Interviewers want to see negative, boundary and auth cases. A suite that only checks 200 responses is not a suite — it is a smoke test.
Hard-coding URLs and tokens
Base URLs, credentials and IDs must come from environment variables or config files. Hard-coding them makes the suite brittle and impossible to run against multiple environments.
Asserting on the whole response body
Asserting every field makes tests break whenever the API adds a new field. Assert on the contract and the fields that matter for the scenario.
Ignoring idempotency and cleanup
Tests that create data but never delete it will eventually fail on duplicates or pollute the environment. Always clean up after yourself.
Not knowing the status codes
Being unsure whether a duplicate email should be 400 or 409 is a red flag. Learn the common codes and the situations that produce them.
Reading code instead of writing it
You will not remember how to chain requests in Postman or write a REST Assured POST by reading it three times. Write it once by hand, then again without looking.
Practise these topics with Uncodemy
Uncodemy's Software Testing program covers manual testing, SQL, API testing with Postman and REST Assured, Selenium with Java, TestNG, Maven and Jenkins. This is the direct path for the topics on this page.
| Program | What it covers | Duration / fee |
|---|---|---|
| Software Testing | Manual testing, SQL, API testing (Postman, REST Assured), Selenium with Java, TestNG, Maven, Jenkins, JIRA. This is the API track. | ₹20,650 + GST · 4–5 months |
| API Automation Testing | REST Assured, Postman, JSON schema validation, framework design. Fee and duration vary; ask a counsellor. | Ask a counsellor for current batch details. |
| Automation Testing | 90+ hours, 45+ live sessions. Selenium WebDriver with Java, TestNG, Maven, Jenkins, POM/hybrid frameworks, Cucumber. | Ask a counsellor for current batch details. |
Placement assistance (as published by Uncodemy): resume building, LinkedIn optimisation, portfolio review, interview preparation, mock interviews and opportunity sharing through a network of 850+ companies. Uncodemy does not guarantee employment, as hiring decisions rest with employers. See placement support.
Also useful: AI career guidance for picking a path, and the 2-class free trial to see how a live batch runs before you commit.