0% found this document useful (0 votes)
3 views15 pages

REST API Testing Interview Guide

This document serves as a comprehensive guide for REST API testing, covering fundamental concepts, HTTP methods, status codes, request and response structures, and validation techniques. It emphasizes the importance of authentication, authorization, and tools like Postman and REST Assured for effective API testing. Additionally, it discusses advanced topics such as JSON schema validation, contract testing, and negative testing strategies.

Uploaded by

a.cayal03
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views15 pages

REST API Testing Interview Guide

This document serves as a comprehensive guide for REST API testing, covering fundamental concepts, HTTP methods, status codes, request and response structures, and validation techniques. It emphasizes the importance of authentication, authorization, and tools like Postman and REST Assured for effective API testing. Additionally, it discusses advanced topics such as JSON schema validation, contract testing, and negative testing strategies.

Uploaded by

a.cayal03
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

REST API Testing

Complete Interview Preparation Guide


From Beginner Concepts to Mid-Level Professional Knowledge | 5 Years Experience Level

1. What is an API? (The Basics)


Before testing APIs, you need to understand what they are. Think of an API like a waiter in a restaurant.

Analogy What it means in APIs


You (the customer) The client app (browser, mobile app, Postman)
The waiter The API
The kitchen The server / backend system
Your food order The API request (what you ask for)
The food delivered The API response (what you get back)

REST (Representational State Transfer) is a style of building APIs. A REST API uses HTTP — the
same protocol your browser uses — to send and receive data. REST APIs are the most common type
of API you will test in a QA role.

2. HTTP Methods — The Core Verbs


Every REST API call uses an HTTP method. These tell the server what action to perform.

Method Action Real-world example Idempotent?


GET Fetch / Read data Get list of all users Yes
POST Create new data Create a new user account No
PUT Replace entire record Replace all user profile fields Yes
Method Action Real-world example Idempotent?
PATCH Update partial record Change only the user's email Yes
DELETE Remove a record Delete a user account Yes

What does Idempotent mean?


Calling the same request multiple times produces the same result. GET /users/1 will always return
the same user. But POST /users called 3 times will create 3 users — so it is NOT idempotent.
Interviewers love this question.

3. HTTP Status Codes — Know These Cold


Status codes tell you whether an API call succeeded or failed. Every QA engineer must know these by
memory.

2xx — Success
Code Meaning & When you see it
200 OK Standard success. GET, PUT, PATCH requests that work correctly return this.
201 Created A new resource was successfully created. Returned after a successful POST.
204 No Success, but no response body. Common for DELETE requests.
Content

4xx — Client Errors (Your mistake)


Code Meaning & When you see it
400 Bad The request is malformed — missing field, wrong data type, invalid JSON.
Request
401 You are not authenticated. Missing or invalid token/credentials.
Unauthorized
403 You are authenticated but do not have permission. Different from 401.
Forbidden
404 Not The resource does not exist. Wrong URL or the record was deleted.
Found
405 Method You used the wrong HTTP method (e.g. POST on a read-only endpoint).
Not Allowed
409 Conflict Resource conflict — e.g. trying to create a user with an email that already exists.
422 Request is understood but fails validation rules (e.g. invalid email format).
Unprocessab
le
429 Too Rate limit exceeded. You sent too many requests in a short time.
Many
Code Meaning & When you see it
Requests

5xx — Server Errors (Their mistake)


Code Meaning & When you see it
500 Internal Something went wrong on the server. Generic error — investigate server logs.
Server Error
502 Bad Server received an invalid response from an upstream service.
Gateway
503 Service Server is down or overloaded. Could be planned maintenance or a crash.
Unavailable
504 Gateway Upstream server did not respond in time. Common in microservices.
Timeout

Interview Tip: 401 vs 403


This is a very common interview question. 401 means you are not logged in at all (unauthenticated).
403 means you are logged in but you are not allowed to access that resource (unauthorized).
Example: a regular user trying to access an admin-only endpoint gets a 403, not a 401.

4. Anatomy of an API Request & Response


Every API call has these parts. You must understand all of them to test effectively.

4.1 Request Structure


Request Line
This is the first line of any HTTP request. It has three parts:
POST [Link] HTTP/1.1
• POST — the HTTP method
• [Link] — the URL (endpoint)
• HTTP/1.1 — the protocol version

Headers
Headers carry metadata about the request — who you are, what format you're sending, what you
accept back.
Content-Type: application/json // Format of the request body
Accept: application/json // Format you want in the response
Authorization: Bearer eyJhbGci... // Your auth token
X-Request-ID: abc-123 // Custom header (tracing/correlation)
Query Parameters
Used to filter, sort, or paginate GET requests. They appear after a '?' in the URL.
GET /users?page=2&limit=50&status=active&sort=created_at
^-----^ ^-------^ ^-----------^ ^--------------^
page items/pg filter sort field

Path Parameters
Used to identify a specific resource. They are part of the URL itself.
GET /users/{userId} -> GET /users/12345
PUT /users/{userId}/address -> PUT /users/12345/address
DEL /orders/{orderId} -> DEL /orders/9876

Request Body
Used with POST, PUT, PATCH. This is the actual data you are sending, usually in JSON format.
{
"name": "Priya Sharma",
"email": "priya@[Link]",
"role": "analyst",
"age": 28
}

4.2 Response Structure


Status Line + Headers
HTTP/1.1 201 Created
Content-Type: application/json
Location: /users/12345
X-Request-ID: abc-123

Response Body
{
"id": "12345",
"name": "Priya Sharma",
"email": "priya@[Link]",
"created_at": "2026-06-04T09:30:00Z",
"status": "active"
}

5. What to Validate in an API Response


When you receive an API response, you should validate all of the following. This is the core of API
testing.

Validation Area What to check


Status Code Is it the expected code? (e.g. 200 for GET, 201 for POST, 204 for
DELETE)
Validation Area What to check
Response Time Is the response within the agreed SLA? (e.g. < 500ms for most APIs)
Response Body Structure Are all expected fields present? Are no extra unexpected fields
returned?
Data Types Is 'age' a number, not a string? Is 'created_at' a proper timestamp?
Field Values Are the returned values correct and matching what was sent?
Null / Empty Handling Are optional fields null or omitted cleanly? No 'null' as string?
Schema Validation Does the response match the documented JSON Schema or contract?
Headers Correct Content-Type? Auth headers present? CORS headers correct?
Error Messages Are error responses descriptive and consistent in format?
Pagination Are page, limit, totalCount, nextPage fields correct?

6. Authentication & Authorization Testing


Authentication (who are you?) and Authorization (what are you allowed to do?) are critical areas to test.
Most security bugs live here.

6.1 Types of Authentication


Type How it works Where you'll see it
Basic Auth Base64 encoded username:password Legacy systems, internal tools
in header
API Key Fixed key passed in header or query Third-party APIs, simple services
param
Bearer Token (JWT) Token issued at login, sent in Most modern REST APIs
Authorization header
OAuth 2.0 User grants permission, app gets Social login, enterprise apps
access token
Client Certificates Certificate-based mutual High-security B2B APIs
(mTLS) authentication

6.2 JWT — Deep Dive (Very Common in Interviews)


JWT (JSON Web Token) is the most common auth mechanism you will encounter. A JWT has 3 parts
separated by dots:
eyJhbGciOiJSUzI1NiJ9 . eyJ1c2VySWQiOiIxMjM0NSJ9 . SflKxwRJSMeKKF2QT4fwpM
^----- HEADER -------^ ^--------- PAYLOAD --------^ ^------ SIGNATURE ------^
• Header: Algorithm used to sign the token (e.g. HS256, RS256)
• Payload: Claims — userId, roles, expiry time (exp), issued-at (iat)
• Signature: Verifies the token has not been tampered with
What to test with JWTs
• Valid token — normal happy path
• No token provided — should return 401
• Expired token — should return 401 with a clear message
• Tampered token (modify payload manually) — should return 401
• Token with insufficient role — should return 403
• Token from wrong environment (staging token on prod) — should be rejected

6.3 Authorization Test Scenarios


These are the scenarios interviewers expect a 5-year QA to design without prompting:
• Role-based access: admin can DELETE, regular user cannot — test both
• Horizontal privilege escalation: User A cannot access User B's data
• Vertical privilege escalation: non-admin cannot call admin endpoints
• Token after logout / revocation should be invalid
• Read-only token should fail on write operations

7. Testing with Postman — Practical Knowledge


Postman is the most commonly used tool for manual API testing. You should know it deeply.

7.1 Key Postman Features


• Collections: Group related requests together (e.g. 'User Management', 'Orders')
• Environments: Store variables like base URL, tokens for dev/staging/prod. Never hardcode
URLs.
• Pre-request Scripts: Run JavaScript before a request — e.g. generate a timestamp, set a token
• Tests Tab: Write assertions in JavaScript that run after the response is received
• Collection Runner: Run an entire collection of requests in sequence, like a test suite
• Newman: CLI tool to run Postman collections from terminal and CI/CD pipelines
• Mock Servers: Simulate API responses when the real API is not ready yet

7.2 Writing Tests in Postman (Must Know)


Every test in Postman uses [Link]() and [Link](). Know these patterns:
// 1. Check status code
[Link]("Status is 200", function () {
[Link](200);
});

// 2. Check response time


[Link]("Response time < 500ms", function () {
[Link]([Link]).[Link](500);
});

// 3. Check a field value


const res = [Link]();
[Link]("User name is correct", function () {
[Link]([Link]).[Link]("Priya Sharma");
});

// 4. Check field type


[Link]("ID is a string", function () {
[Link]([Link]).[Link].a("string");
});

// 5. Chain environment variable from response (login -> use token)


[Link]("authToken", res.access_token);

7.3 Environment Variables — Best Practice


// In Environment: base_url = [Link]
// In request URL: {{base_url}}/users/{{userId}}
// To switch from staging to prod: just change the environment, not every URL

8. API Testing with REST Assured (Java)


REST Assured is the go-to Java library for automation API testing. Your resume shows REST Assured
experience — be ready to write code in interviews.

8.1 Basic GET Request


import [Link].*;
import static [Link].*;
import static [Link].*;

given()
.baseUri("[Link]
.header("Authorization", "Bearer " + token)
when()
.get("/users/12345")
then()
.statusCode(200)
.body("name", equalTo("Priya Sharma"))
.body("email", notNullValue())
.time(lessThan(500L)); // response time in ms

8.2 POST Request with JSON Body


String requestBody = "{\"name\": \"Priya\", \"email\": \"priya@[Link]\"}";

given()
.baseUri("[Link]
.contentType([Link])
.header("Authorization", "Bearer " + token)
.body(requestBody)
when()
.post("/users")
then()
.statusCode(201)
.body("id", notNullValue())
.header("Location", containsString("/users/"));

8.3 Extracting Values from Response


// Extract a single field
String userId = given().when().get("/users/me")
.then().extract().path("id");

// Extract the full response as a JsonPath object


Response response = given().when().get("/users/12345").then().extract().response();
String name = [Link]().getString("name");
List<String> roles = [Link]().getList("roles");

8.4 Schema Validation with REST Assured


// Add dependency: rest-assured-json-schema-validator
import static [Link].*;

given().when().get("/users/12345")
.then()
.statusCode(200)
.body(matchesJsonSchemaInClasspath("schemas/[Link]"));

9. JSON Schema Validation


JSON Schema defines the expected structure of a JSON response. It is like a contract between the
frontend and backend.

9.1 Example JSON Schema


{
"$schema": "[Link]
"type": "object",
"required": ["id", "name", "email"],
"properties": {
"id": { "type": "string" },
"name": { "type": "string", "minLength": 1 },
"email": { "type": "string", "format": "email" },
"age": { "type": "integer", "minimum": 18 },
"roles": { "type": "array", "items": { "type": "string" } }
},
"additionalProperties": false
}

9.2 What Schema Validation catches


• A field that was supposed to be a number is returned as a string
• A required field is missing from the response
• A new unexpected field is added to the response (breaking change for consumers)
• An array that should contain strings is empty or contains objects
• A date field is not in the correct ISO 8601 format

Key Interview Point


Schema validation is contract testing at the field level. It ensures both the field names and data types
match what was agreed. Your resume mentions this — be ready to explain why it matters in CI/CD
pipelines (catch breaking changes before they reach production).

10. Contract Testing


Contract testing checks the agreement (contract) between a consumer (frontend or another service)
and a provider (the API). It is more advanced than schema validation.

10.1 Consumer-Driven Contract Testing (CDCT)


• The consumer defines what it expects from the API
• The provider verifies it can meet those expectations
• Changes to the API that would break a consumer are caught early
• The most popular tool for this is Pact

10.2 Contract vs Schema vs Integration Testing


Type What it checks When it runs
Schema Validation Response structure matches a JSON Every test execution
Schema
Contract Testing Provider meets all consumer As part of CI/CD pipeline
expectations
Integration Testing End-to-end flow between two In staging/pre-prod environments
systems works

11. Negative Testing & Boundary Testing


A mid-level QA is expected to design negative test cases without being told. These are the categories:

11.1 Input Validation Tests


Scenario What you send Expected result
Missing required field POST body without 'email' 400 Bad Request
Wrong data type age: "twenty-eight" (string) 400 or 422
Empty string on required name: "" 400 or 422
Scenario What you send Expected result
Null on required field name: null 400 or 422
Extra unexpected fields Add 'hackField' to body Should be ignored or 400
Invalid email format email: "notanemail" 422 Unprocessable
SQL Injection name: "'; DROP TABLE users; 400 (sanitized, no crash)
--"
XSS in field name: "<script>alert(1)</script>" Escaped or rejected

11.2 Boundary & Limit Tests


• String field with max length: exactly at limit, one over the limit
• Numeric field: minimum value, maximum value, zero, negative numbers
• Integer overflow: send 99999999999999 where small int is expected
• Empty array vs null array — often handled differently
• Date fields: past dates, future dates, invalid dates (Feb 30), epoch zero
• Pagination: page=0, page=-1, limit=0, limit=99999

11.3 Authentication Negative Tests


• No Authorization header at all
• Malformed token (random string, not a valid JWT)
• Expired JWT token
• Token signed with wrong secret
• Token for a deleted/deactivated user
• Wrong HTTP scheme (Basic instead of Bearer)

12. API Test Design — The Testing Checklist


For every API endpoint you test, go through this structured checklist. This is the difference between a
junior tester and a mid-level analyst.

Test Case Category

1 Happy path — valid inputs, valid auth, expected response


2 All required fields present / each required field removed one at a time
3 Optional fields — with and without each optional field
4 Boundary values — min, max, at limit, just over limit
5 Invalid data types for each field
6 No auth token, expired token, wrong role token
7 Non-existent resource ID (404 scenarios)
Test Case Category

8 Duplicate creation (e.g. same email twice — 409 expected)


9 Pagination: first page, last page, page beyond range, invalid page
10 Concurrency: same resource updated simultaneously (race condition)
11 Large payload / too many records in array
12 Special characters, unicode, emojis in string fields
13 Correct HTTP method (verify wrong methods return 405)
14 Response schema matches contract (JSON Schema validation)

13. API Testing in CI/CD Pipelines


At your experience level, understanding where API testing fits in a CI/CD pipeline is expected. You
mentioned Jenkins and Bitbucket Pipelines in your resume — be ready to explain this.

13.1 The Pipeline Flow


• Code commit triggers the pipeline
• Unit tests run first (fastest, developers own these)
• API/integration tests run next (QA-owned, use REST Assured or Newman)
• Contract tests validate the API still meets consumer expectations
• Performance smoke tests check response times haven't regressed
• If all pass: deploy to staging. If any fail: pipeline stops, team is notified

13.2 Running Postman Tests in CI (Newman)


# Install Newman globally
npm install -g newman

# Run a Postman collection against staging environment


newman run UserAPI.postman_collection.json \
--environment staging.postman_environment.json \
--reporters cli,junit \
--reporter-junit-export results/[Link]

13.3 Running REST Assured Tests in Jenkins


// In Jenkinsfile (declarative pipeline)
stage('API Tests') {
steps {
sh 'mvn test -Dtest=UserAPITests -[Link]=false'
}
post {
always {
junit 'target/surefire-reports/*.xml'
}
}
}

14. Performance & Load Testing Basics


As a mid-level QA, you are expected to understand API performance testing even if you don't run it
daily. Your resume mentions JMeter — know this section well.

14.1 Key Performance Metrics


Metric What it means
Response Time How long from request sent to response received (milliseconds)
Throughput (TPS) Transactions Per Second — how many requests the API handles per
second
Error Rate Percentage of requests that returned 4xx or 5xx responses
Latency (P95/P99) 95th/99th percentile response time — worst-case performance for most
users
Concurrent Users How many users are hitting the API at the same time
CPU / Memory Server resource utilization under load

14.2 Types of Performance Tests


• Load Test: Normal expected traffic — verify the API meets SLAs under typical conditions
• Stress Test: Push beyond normal limits — find the breaking point
• Spike Test: Sudden surge in traffic (e.g. flash sale) — does the API recover?
• Soak Test: Run normal load for hours/days — find memory leaks and gradual degradation
• Smoke Test: Quick performance check — just verify response times haven't spiked after a
deploy

15. Security Testing for APIs


Security testing is increasingly expected from mid-level QA engineers. You don't need to be a
penetration tester, but you must know the common vulnerabilities.

15.1 OWASP API Security Top 10 (Must Know)


# Vulnerability How to test it
1 Broken Object Level Auth Access User B's data with User A's token (IDOR)
2 Broken Auth Use expired / invalid / no token — should all return 401
3 Broken Object Property Auth Request or send fields you shouldn't have access to
# Vulnerability How to test it
4 Unrestricted Resource Send limit=999999 or huge payloads — should be throttled
Consumption
5 Broken Function Level Auth Non-admin calling admin-only endpoints
6 Mass Assignment POST body with 'role: admin' — server should ignore it
7 Security Misconfiguration Check headers: CORS, X-Content-Type, HTTPS enforcement
8 Injection SQL/NoSQL/command injection in any input field
9 Improper Inventory Mgmt Access old/deprecated API versions that still work
1 Unsafe API Consumption API consumes third-party data without validation
0

15.2 Important Security Headers to Check


• Strict-Transport-Security: Ensures HTTPS is enforced (HSTS)
• X-Content-Type-Options: nosniff: Prevents MIME-type sniffing attacks
• X-Frame-Options: Prevents clickjacking
• Content-Security-Policy: Controls what resources can be loaded
• Access-Control-Allow-Origin: CORS — who is allowed to call this API

16. API Versioning


APIs evolve. Versioning lets old clients keep working while new features are added. Know the
approaches:

Strategy Example Notes


URL Path (most /api/v1/users vs /api/v2/users Easy to read, test, and route
common)
Query Parameter /api/users?version=2 Flexible but harder to cache
Header-based Accept: application/[Link].v2+json Clean URLs, harder to test manually

Testing Versioning
• Ensure old API version still works after new version is deployed
• Verify deprecated endpoints return clear deprecation warnings
• Test that old clients on v1 are not affected by v2 changes
• Check that version mismatch returns appropriate error (not a 500)
17. Common Interview Questions & Model Answers
These are the most frequently asked REST API testing questions at the mid-level analyst interview
stage.

Q1: What is the difference between PUT and PATCH?


PUT replaces the entire resource — if you PUT a user object with only the 'name' field, all other fields
(email, role, phone) will be set to null or removed. PATCH updates only the fields you provide — if
you PATCH with just 'name', only the name changes. Always verify this behavior in testing: send a
PATCH with one field and confirm others are unchanged.

Q2: How do you test an API when there is no UI?


Use tools like Postman for manual exploration and validation. Write automated tests using REST
Assured (Java) or requests library (Python). Test directly using curl from the command line for quick
checks. Review API documentation (Swagger/OpenAPI) to understand expected inputs and outputs.
Design test cases based on requirements and execute them against the API endpoint directly.

Q3: What is the difference between 401 and 403?


401 Unauthorized means the request has no authentication credentials or they are invalid — the
server does not know who you are. 403 Forbidden means the server knows who you are (valid token)
but you do not have permission to access that resource. Think of it this way: 401 is 'Who are you?'
and 403 is 'I know who you are, but you cannot come in here.'

Q4: What is idempotency and why does it matter in API testing?


An idempotent operation produces the same result no matter how many times you call it. GET, PUT,
DELETE, and PATCH are idempotent — calling them 10 times has the same effect as calling them
once. POST is NOT idempotent — calling POST 10 times creates 10 records. This matters in testing
because you need to verify: (a) idempotent methods behave correctly when retried, and (b) non-
idempotent methods create exactly one record and no duplicates from retries.

Q5: How do you handle authentication in your API tests?


For Postman: store tokens in environment variables and use pre-request scripts to refresh them
when expired. For REST Assured: use a @BeforeClass setup method that calls the login endpoint,
extracts the token, and injects it into all subsequent requests. For CI/CD: store credentials as
encrypted environment variables in Jenkins/Bitbucket, never hardcode them. Always test the token
refresh flow and expired token scenarios.

Q6: What is JSON Schema Validation and why do you use it?
JSON Schema Validation checks that the API response matches a predefined structure — correct
field names, correct data types, required fields present, no unexpected extra fields. It acts as a
contract between the API producer and consumer. In your CI pipeline, it catches breaking changes
automatically — if a developer accidentally renames a field from 'user_id' to 'userId', the schema
validation fails immediately before it reaches production and breaks other services.
Q7: Walk me through how you would test a POST /users endpoint from scratch.
First, review the API documentation/Swagger to understand required and optional fields, data types,
and expected responses. Then design test cases: (1) happy path with all valid required fields, (2)
each required field missing one at a time, (3) invalid data types, (4) boundary values, (5) duplicate
email creation, (6) no auth token, (7) correct 201 status and Location header in response, (8) schema
validation on the response body. Execute in Postman first to explore, then automate using REST
Assured for regression.

18. Tools Quick Reference


Tool Category Primary use in API testing
Postman Manual + Automation Explore, test, and automate API calls with
assertions
Newman CI/CD Runner Run Postman collections from terminal and
pipelines
REST Assured Automation (Java) Write automated API tests integrated with
TestNG/JUnit
Swagger / OpenAPI Documentation Understand API contract; test directly from
Swagger UI
JMeter Performance Load and stress testing for APIs
Pact Contract Testing Consumer-driven contract testing between
services
curl Command-line Quick API calls from terminal without a GUI tool
Wiremock Mocking Mock API responses for testing when real API
unavailable
OWASP ZAP Security Automated security scanning of API endpoints
JIRA + Zephyr Test Management Track test cases, defects, and execution results

Good luck with your interviews!


Your 5 years of real project experience — GCP migration, banking regulatory reporting, AI-assisted
testing — is your biggest asset. Let the stories from your projects do the talking.

You might also like