Autocoder

API Testing and Postman Interview Questions

Last updated 2026-11-19

API testing questions check that you understand HTTP deeply, can design meaningful test cases beyond the happy path, and can automate them. This page gives 16 worked answers: methods and status codes, idempotency, authentication, Postman test scripts and environments, chaining requests, running collections in CI with Newman, schema validation, and the same checks written with REST Assured and Python.

Everything is kept consistent with current Postman behaviour, where scripts use the pm object. For the broader testing picture see the automation testing questions, the manual testing questions and the SDET questions. For interview tactics read how to crack a QA testing interview.

Key HTTP ideasMethods, idempotency, status codes, headers, content negotiation, caching, statelessness
ToolsPostman and Newman, REST Assured, Python requests with pytest, cURL, Swagger or OpenAPI
Test categoriesFunctional, validation, auth, error handling, contract, performance, security

A Postman test script you should be able to write

This script goes in the Tests tab of a request. It checks status, response time, headers and body, validates against a schema, and saves an ID into a collection variable so the next request can use it.

javascript
pm.test('status is 201', () => pm.response.to.have.status(201));
pm.test('responds within 800 ms', () => pm.expect(pm.response.responseTime).to.be.below(800));
pm.test('JSON content type', () => pm.response.to.have.header('Content-Type', /application\/json/));

const body = pm.response.json();
pm.test('body has expected fields', () => {
  pm.expect(body).to.have.property('id');
  pm.expect(body.email).to.eql(pm.variables.get('email'));
});

const schema = {
  type: 'object',
  required: ['id', 'email', 'createdAt'],
  properties: { id: { type: 'integer' }, email: { type: 'string' }, createdAt: { type: 'string' } }
};
pm.test('matches schema', () => pm.response.to.have.jsonSchema(schema));

pm.collectionVariables.set('userId', body.id);

API Testing and Postman Interview Questions: questions with worked answers

  1. 1

    What is API testing, and why is it done before UI testing?

    easy

    API testing sends requests directly to a service's interface and verifies responses, status codes, headers, data and behaviour, with no user interface involved. It is faster and more stable than UI testing, finds defects closer to the source, covers business logic, error handling and security rules that a UI never exposes, and can start as soon as the endpoint exists, before the front end is built. Because most of an application's risk sits in its services, a well-tested API layer lets you keep UI automation small. The tests check contract, correctness, performance, security and resilience.

  2. 2

    Explain the HTTP methods and which are safe and idempotent.

    easy

    GET retrieves a resource and is safe (no side effects) and idempotent. HEAD is like GET without a body, also safe and idempotent. POST creates a resource or triggers processing, and is neither safe nor idempotent, so repeating it can create duplicates. PUT replaces a resource at a known URL and is idempotent. PATCH partially updates and is not guaranteed idempotent. DELETE removes a resource and is idempotent, since deleting twice leaves the same state even if the second response is 404. OPTIONS describes allowed methods and is used in CORS preflight. Idempotency matters for safe retries after timeouts, and APIs often add idempotency keys to make POST retryable.

  3. 3

    Which HTTP status codes should you know, and how do you test them?

    easy

    2xx success: 200 OK, 201 Created (with a Location header), 202 Accepted, 204 No Content. 3xx redirection: 301, 302, 304 Not Modified. 4xx client errors: 400 Bad Request for malformed or invalid input, 401 Unauthorized for missing or invalid authentication, 403 Forbidden for authenticated but not allowed, 404 Not Found, 405 Method Not Allowed, 409 Conflict, 415 Unsupported Media Type, 422 Unprocessable Content for semantic validation errors, 429 Too Many Requests. 5xx server errors: 500, 502, 503, 504. Test each documented code with a request that triggers it, and confirm the body has a consistent error format. A 500 caused by user input is a defect: validation should return 4xx.

  4. 4

    What is the difference between 401 and 403, and between PUT and PATCH?

    medium

    401 means the server does not know who you are: credentials are missing, invalid or expired, and the response should include a WWW-Authenticate header. 403 means the server knows who you are but you are not permitted to do this, so re-authenticating will not help. Test both: no token gives 401; a valid token for a normal user calling an admin endpoint gives 403; and another user's resource gives 403 or 404 depending on whether existence should be hidden. PUT replaces the whole resource, so omitted fields may be reset, while PATCH changes only the fields supplied.

  5. 5

    Design test cases for a POST /users endpoint.

    medium

    Positive: valid body returns 201 with a Location header and the created resource, and a subsequent GET returns it. Validation: missing required fields, wrong types, empty strings, maximum lengths, invalid email format, boundary values and extra unknown fields, each returning 400 or 422 with a helpful message. Business rules: duplicate email returns 409. Auth: no token 401, insufficient role 403. Format: wrong Content-Type returns 415, malformed JSON returns 400. Security: injection strings stored or rejected safely, mass assignment of fields like role or isAdmin ignored, passwords never returned. Non-functional: response time, rate limiting and behaviour under concurrent duplicate requests.

  6. 6

    How do environments and variables work in Postman, and what is their scope order?

    medium

    Variables hold values such as base URLs and tokens, referenced as double curly braces. Scopes from narrowest to widest are local (a single run), data (from a CSV or JSON file in the runner), environment, collection and global; when names clash, the narrower scope wins. Use environments to switch between dev, staging and production with the same collection, keep secrets in the initial value left blank and the current value local, or use a vault, and never commit real tokens to a shared workspace. Set variables from scripts with pm.environment.set or pm.collectionVariables.set.

  7. 7

    How do you chain requests in Postman, for example login then use the token?

    medium

    In the Tests tab of the login request, parse the response and store the token in a variable; subsequent requests use it in the Authorization header with the variable reference, or inherit authentication set at the collection level. Order requests in a folder so the runner executes them in sequence, and use pm.execution.setNextRequest, or its older pm.setNextRequest, only when you need to branch or loop. A pre-request script can refresh the token when it is near expiry so long runs do not fail on expiry.

    javascript
    // Tests tab of POST /auth/login
    const res = pm.response.json();
    pm.test('login ok', () => pm.response.to.have.status(200));
    pm.environment.set('token', res.accessToken);
    pm.environment.set('tokenExpiry', Date.now() + res.expiresIn * 1000);
    
    // Pre-request script at collection level: refresh when close to expiry
    if (!pm.environment.get('token') || Date.now() > Number(pm.environment.get('tokenExpiry')) - 30000) {
      pm.sendRequest({
        url: pm.environment.get('baseUrl') + '/auth/login',
        method: 'POST',
        header: { 'Content-Type': 'application/json' },
        body: { mode: 'raw', raw: JSON.stringify({ user: pm.environment.get('user'), pass: pm.environment.get('pass') }) }
      }, (err, resp) => {
        if (!err) {
          const j = resp.json();
          pm.environment.set('token', j.accessToken);
          pm.environment.set('tokenExpiry', Date.now() + j.expiresIn * 1000);
        }
      });
    }
  8. 8

    What authentication methods do APIs use, and how do you test them?

    medium

    Basic auth sends a base64 username and password and must run over HTTPS. API keys are static secrets sent in a header or query. Bearer tokens, commonly JWTs, are issued after login and sent in the Authorization header. OAuth 2.0 issues access tokens through flows such as authorisation code with PKCE or client credentials. Test valid, missing, malformed, expired and tampered tokens, tokens for the wrong audience or scope, token reuse after logout where revocation is promised, and that secrets are never accepted in URLs. A JWT with the alg set to none or an altered payload must be rejected.

  9. 9

    How do you run a Postman collection in CI with Newman?

    medium

    Newman is Postman's command-line runner. Export the collection and environment as JSON or run them from the Postman API, execute newman run with reporters, and let the exit code fail the pipeline when any assertion fails. Pass secrets as environment variables, not committed files, use iteration data for data-driven runs, and publish the JUnit or HTML report as a CI artefact. Newman needs Node.js, and the Postman CLI is the newer official alternative that runs collections from your workspace.

    bash
    npm install -g newman newman-reporter-htmlextra
    newman run collection.json -e staging.json \
      --env-var "token=$API_TOKEN" \
      -d users.csv --iteration-count 3 \
      --reporters cli,junit,htmlextra --reporter-junit-export results.xml
  10. 10

    What is JSON schema validation and why is it useful in API tests?

    medium

    A JSON Schema describes the expected structure of a response: required properties, types, formats, enumerations and value ranges. Asserting against a schema catches contract changes such as a field renamed, a number turned into a string, or an extra null, in one assertion instead of dozens of field checks. Combine it with a few business-value assertions. Keep schemas in version control, or generate them from an OpenAPI document so the contract is a single source of truth. Be careful with additionalProperties: false, which makes tests fail on harmless additive changes.

  11. 11

    Write the same API test in REST Assured (Java) and in Python.

    medium

    Both express the same steps: send a request, assert on status, headers and body, and extract values for later calls. REST Assured has a given, when, then fluent syntax with Hamcrest matchers and JSON path. In Python, requests with pytest keeps it explicit and easy to parametrise. In either, set a timeout, never hard-code secrets and keep the base URL configurable.

    java
    import static io.restassured.RestAssured.*;
    import static org.hamcrest.Matchers.*;
    
    given()
        .baseUri("https://api.example.test")
        .header("Authorization", "Bearer " + token)
        .contentType("application/json")
        .body("{\"email\":\"asha@example.test\"}")
    .when()
        .post("/users")
    .then()
        .statusCode(201)
        .header("Location", containsString("/users/"))
        .body("email", equalTo("asha@example.test"))
        .time(lessThan(800L));
    python
    import requests
    
    def test_create_user(base_url, token):
        r = requests.post(f'{base_url}/users',
                          json={'email': 'asha@example.test'},
                          headers={'Authorization': f'Bearer {token}'}, timeout=10)
        assert r.status_code == 201
        assert '/users/' in r.headers['Location']
        assert r.json()['email'] == 'asha@example.test'
        assert r.elapsed.total_seconds() < 0.8
  12. 12

    What is the difference between REST and SOAP, and what is GraphQL?

    medium

    REST is an architectural style using HTTP verbs on resource URLs, typically JSON, stateless and cache-friendly. SOAP is a protocol with XML envelopes, a WSDL contract, standards such as WS-Security and strict typing, still found in banking and enterprise integrations. GraphQL exposes a single endpoint where clients specify exactly the fields they want, avoiding over- and under-fetching, with a typed schema; testing it needs query-level and authorisation tests per field, and attention to expensive nested queries and introspection exposure. In Postman, GraphQL requests have their own body mode, and SOAP is sent as XML with the right Content-Type.

  13. 13

    How do you test an API for security problems?

    hard

    Use the OWASP API Security Top 10 as a checklist. Test broken object-level authorisation by calling one user's resource with another user's token; broken authentication by trying missing, expired and forged tokens; excessive data exposure by checking responses for fields the client should not see; mass assignment by sending extra properties like role; lack of rate limiting by sending bursts; injection with special characters in parameters; improper CORS and security headers; and verbose error messages leaking stack traces. Only test systems you are authorised to test, ideally non-production.

  14. 14

    How do you test pagination, filtering and sorting?

    medium

    For pagination, verify the first, middle and last pages, the page-size limit and default, an out-of-range page returning an empty list or an error as documented, no duplicates or gaps across pages, and a consistent total count; with cursor-based pagination, verify stability while items are inserted. For filtering, test single and combined filters, no-match results, invalid values and case handling. For sorting, check ascending and descending order against a locally sorted copy, tie-breaking, and null handling. Validate the metadata, such as next links, and ensure expensive queries have sensible limits.

  15. 15

    What is contract testing and how does it differ from end-to-end API tests?

    hard

    Contract testing verifies that a provider and its consumers agree on the shape and behaviour of an interface without running the whole system. In consumer-driven contracts, such as with Pact, each consumer records the requests it makes and the responses it needs; the provider verifies it can satisfy them in its own pipeline. This catches breaking changes early, runs fast and isolates failures, whereas end-to-end tests need all services deployed and are slower and flakier. They complement each other: contracts guard integration points and a few end-to-end tests confirm full journeys.

  16. 16

    A GET /orders/{id} endpoint is slow only sometimes. How would you investigate as a tester?

    hard

    Collect evidence first: record response times across many calls, with timestamps, parameters and response sizes, to see whether slowness correlates with specific IDs, large orders, time of day or cache misses. Compare the first and repeat calls to spot caching effects, test with and without concurrency, and inspect response headers such as server timing or trace IDs. Share the trace ID with developers so they can follow the request in logs and APM. Then write a repeatable performance test, for example in JMeter, that demonstrates the pattern. See the JMeter questions.

Frequently asked questions

Is Postman enough for an API testing job?

It is a good start and common in interviews, but employers also expect an automated approach in code, such as REST Assured or Python requests, and CI integration through Newman or the Postman CLI.

What is the difference between API testing and unit testing?

Unit tests check one function in isolation, usually with mocks. API tests exercise the deployed service interface over HTTP, including routing, serialisation, authentication and often the database.

What is Swagger or OpenAPI?

OpenAPI is a standard, machine-readable description of a REST API; Swagger tools render and test it. You can import it into Postman to generate requests and use it as the basis for contract validation.

Which free public APIs can I practise with?

Several public sandbox APIs exist for practice, and you can also run a small API of your own locally. Check the current availability and terms of each service before depending on it.

Related guides

More in Role-wise Interview Questions by Job and Tech Stack

See all in this section