100 ESSENTIAL API TESTING: INTERVIEW QUESTIONS & DETAILED TECHNICAL ANSWERS

Comprehensive, production-grade technical interview encyclopedia for B.Tech Automation Engineers, SDETs, and QA Leads: Covering Core API Concepts & Architecture, HTTP Protocols & Payloads, Postman & Newman CLI, Java REST Assured, Python Requests & PyTest, SoapUI & WSDL Web Services, Performance & Security Testing (JMeter & OWASP ZAP), and Advanced Frameworks (Karate, WireMock, Pact & CI/CD Pipelines). Click "Copy Q&A" on any question block to copy the full technical specification.

🔌 Technical Rigor, Protocol Architecture & SDET Quality Engineering

Enterprise API testing demands a deep structural comprehension of underlying network protocols, status codes, serialization engines, and data formats rather than simple point-and-click validation. Modern SDETs and quality engineers are expected to design resilient automation frameworks, implement robust schema validation, automate token-based authentication workflows, execute load simulations, and conduct rigorous security checks. Below are 100 comprehensive technical interview questions categorized across 8 core disciplines, formatted with direct copy-to-clipboard functionality for rapid reference and study.

Section 1: Core API Concepts, Architecture & Protocols (Q1 – Q15)
Foundations of interface architectures, testing pyramid principles, REST constraints, SOAP vs REST, GraphQL, gRPC, and contract definitions.
Q1: API Definition & Significance in Modern Architecture
Q1: What is an Application Programming Interface (API), and why is API testing critical in modern software architectures?

ANSWER:
An API is a computing interface that defines interactions between multiple software intermediaries. It dictates the kinds of calls or requests that can be made, how to make them, the data formats that should be used, and the conventions to follow. API testing operates at the Business Logic layer (Layer 2 in 3-tier architecture). It is critical because:
- It enables testing without dependency on the Graphical User Interface (GUI), shifting defect detection earlier in the SDLC (Shift-Left testing).
- Test execution is significantly faster and less brittle than UI automation.
- It validates business logic, data integrity, security authorization, and compliance before services are exposed to clients or microservice meshes.
Q2: The API Testing Pyramid vs. UI Automation
Q2: What is the API Testing Pyramid, and how does it compare to UI testing?

ANSWER:
Mike Cohn's Testing Pyramid positions API (Service/Integration) testing between Unit tests and UI tests:
- Base (Unit Tests): Highest volume, executed directly against source code methods by developers.
- Middle (API/Service Layer Tests): Tests business rules, integration contracts, database persistence, and external service communication. Fast execution, high resilience to UI layout shifts.
- Top (End-to-End UI Tests): Smallest volume. Validates complete user journeys via browser/app rendering. High maintenance cost and higher execution time.
Q3: RESTful Architecture & Six Roy Fielding Constraints
Q3: What is a RESTful API, and what are the six architectural constraints defined by Roy Fielding?

ANSWER:
REST (Representational State Transfer) is an architectural style designed around network resources. The six guiding constraints are:
1. Client-Server Architecture: Separation of user interface concerns from data storage concerns.
2. Statelessness: Every request from client to server must contain all necessary information to understand and process the request; no session context is stored on the server.
3. Cacheability: Responses must explicitly define themselves as cacheable or non-cacheable to prevent stale client-side data reuse.
4. Uniform Interface: Standardized resource identification (URIs), resource manipulation through representations, self-descriptive messages, and HATEOAS (Hypermedia As The Engine Of Application State).
5. Layered System: The client cannot tell whether it is connected directly to the end server or to an intermediary (load balancer, proxy, CDN).
6. Code on Demand (Optional): Servers can temporarily extend or customize client functionality by transferring executable code (e.g., JavaScript).
Q4: SOAP vs. REST Architectural Comparison
Q4: How does SOAP differ fundamentally from REST?

ANSWER:
- Protocol vs. Architectural Style: SOAP (Simple Object Access Protocol) is a rigid, standardized W3C protocol; REST is a flexible architectural pattern.
- Data Format: SOAP exclusively uses XML wrapped in envelopes (Header and Body); REST supports JSON (predominant), XML, Plain Text, YAML, and Protocol Buffers.
- Transport: SOAP is transport-agnostic (operates over HTTP, SMTP, JMS, TCP); REST almost universally relies on HTTP/HTTPS.
- Contract Definition: SOAP mandates strict formal contracts using WSDL (Web Services Description Language); REST commonly uses OpenAPI/Swagger specifications, which are optional at runtime.
- Security & Standards: SOAP has native WS-Security extensions built-in; REST relies on underlying transport security (TLS/HTTPS) and application tokens (OAuth 2.0/JWT).
Q5: GraphQL Solving Over-fetching & Under-fetching
Q5: What is GraphQL, and how does it resolve the "Over-fetching" and "Under-fetching" problems seen in REST?

ANSWER:
GraphQL is a query language and server-side runtime created by Meta.
- Over-fetching: In REST, an endpoint like /api/users/1 returns an entire user object containing 30 fields when the client only needed the username. GraphQL allows clients to specify exact fields in the query payload:
  query { user(id: 1) { username } }
- Under-fetching: In REST, retrieving a user and their recent orders requires multiple round-trip calls (/users/1 followed by /users/1/orders). GraphQL resolves nested, relational resources in a single HTTP POST request.
Q6: gRPC Architecture & Protocol Buffers
Q6: What is gRPC, and where is it preferred over REST?

ANSWER:
gRPC (Google Remote Procedure Call) is an open-source, high-performance RPC framework.
- Transport: Built natively on HTTP/2, enabling bidirectional streaming, header compression, and multiplexing over a single TCP connection.
- Payload Serialization: Uses Protocol Buffers (Protobuf) instead of textual JSON, serializing data into compact binary representations that parse significantly faster.
- Use Case: High-throughput internal microservice-to-microservice communication, real-time data pipelines, and distributed systems where network bandwidth and serialization latency are critical bottlenecks.
Q7: Synchronous vs. Asynchronous API Architecture
Q7: What are the primary differences between Synchronous and Asynchronous APIs?

ANSWER:
- Synchronous APIs: The client dispatches a request and blocks execution, awaiting an immediate HTTP response (e.g., standard HTTP GET/POST).
- Asynchronous APIs: The client submits a task request, and the server acknowledges receipt immediately (e.g., HTTP 202 Accepted returning a job_id or status polling URL) while processing occurs in the background. Alternatively, asynchronous communication is managed via message brokers (Kafka, RabbitMQ) or event streams (WebSockets, Server-Sent Events).
Q8: API Contract Testing & Regression Prevention
Q8: What is API Contract Testing, and how does it prevent integration regressions?

ANSWER:
Contract testing verifies that two separate services (a Consumer and a Provider) adhere to a shared, agreed-upon agreement (the "contract") covering request headers, URLs, payloads, and response schemas, without requiring both services to be running concurrently in a live integration environment. It detects breaking schema changes early in CI pipelines before deployment.
Q9: Endpoint vs. Resource vs. URI Differentiation
Q9: What is the difference between an API Endpoint, a Resource, and a URI?

ANSWER:
- Resource: The actual conceptual entity or object stored on the server (e.g., a Customer or Order record).
- URI (Uniform Resource Identifier): The identifier used to specify the resource (e.g., /api/v1/customers/101).
- Endpoint: The physical point of entry or URL address exposed by the server where incoming requests can access the resource and service functions (e.g., https://api.domain.com/api/v1/customers/101).
Q10: API Versioning Architectural Strategies
Q10: What is API Versioning, and what are the standard patterns to implement it?

ANSWER:
API versioning manages changes to schemas, behavior, or endpoints over time without breaking existing client integrations.
1. URI Path Versioning (Most Common): https://api.example.com/v1/users vs. /v2/users
2. Query Parameter Versioning: https://api.example.com/users?version=2
3. Custom Request Header Versioning: X-API-Version: 2.0
4. Content Negotiation (Accept Header): Accept: application/vnd.company.v2+json
Q11: The Operational Role of an API Gateway
Q11: What is the purpose of an API Gateway?

ANSWER:
An API Gateway sits between client consumers and internal backend microservices. Key operational responsibilities include:
- Request routing and composition
- Authentication and authorization token validation
- Rate limiting and traffic throttling
- SSL termination
- Centralized telemetry, logging, and metrics aggregation
- API caching and circuit breaking
Q12: Idempotent vs. Safe HTTP Methods
Q12: What is the difference between Idempotent and Safe HTTP methods?

ANSWER:
- Safe Methods: Methods that do not modify server state or produce side-effects (read-only). Examples: GET, HEAD, OPTIONS.
- Idempotent Methods: Methods where executing the request once produces the exact same server resource state as executing it multiple times consecutively. Examples: GET, PUT, DELETE, HEAD, OPTIONS. (Note: POST is neither safe nor idempotent).
Q13: API Virtualization vs. Traditional Mocking
Q13: What is API Virtualization, and how does it differ from traditional Mocking?

ANSWER:
- Mocking: Lightweight, isolated code stubs created within a specific test suite to emulate predefined, static responses for hard-coded endpoints.
- API Virtualization: Deploying enterprise-grade, software-based simulations of complete third-party or unavailable backend services that emulate full protocol behavior, realistic state changes, performance latencies, and diverse error modes across network environments.
Q14: Authentication (AuthN) vs. Authorization (AuthZ)
Q14: Explain the difference between API Authentication and API Authorization.

ANSWER:
- Authentication (AuthN): Validates the identity of the requesting entity ("Who are you?") via API keys, basic credentials, or tokens.
- Authorization (AuthZ): Validates the permissions and rights of the authenticated entity to perform a specific action on a requested resource ("Are you allowed to execute DELETE on this record?").
Q15: OpenAPI / Swagger Specification Architecture
Q15: What is Swagger / OpenAPI Specification (OAS)?

ANSWER:
The OpenAPI Specification is a vendor-neutral, machine-readable interface description standard for HTTP REST APIs written in JSON or YAML. It comprehensively documents available endpoints, HTTP verbs, parameters, payload schemas, security requirements, and sample responses. Tools like Swagger UI ingest OAS definitions to generate interactive sandboxes for manual testing and automated client SDK generation.
Section 2: HTTP Methods, Status Codes, Headers & Payloads (Q16 – Q28)
HTTP verbs, semantic status codes, header mechanics, JWT internals, rate limiting, and content negotiation.
Q16: Complete Replacement (PUT) vs. Partial Update (PATCH)
Q16: Compare PUT versus PATCH HTTP methods.

ANSWER:
- PUT (Complete Replacement): Idempotent. The client transmits the complete resource entity in the payload. Any existing fields not included in the payload are typically cleared or reset to defaults by the server.
- PATCH (Partial Modification): Non-idempotent by specification (though often implemented idempotently). The client transmits only the specific fields intended for mutation; all omitted fields remain unaltered.
Q17: The 5 Major HTTP Status Code Classes
Q17: List the 5 major HTTP status code classes and their semantic meanings.

ANSWER:
- 1xx (Informational): Request received, continuous processing (e.g., 100 Continue, 101 Switching Protocols).
- 2xx (Success): Action successfully received, understood, and accepted (e.g., 200 OK, 201 Created, 204 No Content).
- 3xx (Redirection): Further action required by client to complete the request (e.g., 301 Moved Permanently, 304 Not Modified).
- 4xx (Client Error): The request contains incorrect syntax or cannot be fulfilled by client fault (e.g., 400 Bad Request, 401 Unauthorized, 404 Not Found).
- 5xx (Server Error): The server failed to fulfill an apparently valid request (e.g., 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable).
Q18: HTTP 401 Unauthorized vs. 403 Forbidden
Q18: Differentiate between HTTP 401 Unauthorized and 403 Forbidden.

ANSWER:
- 401 Unauthorized: The request requires valid user authentication credentials. The client has either provided invalid credentials or no credentials at all. The response usually includes a WWW-Authenticate header.
- 403 Forbidden: The server successfully parsed and recognized the client's identity (the client is authenticated), but the client lacks permission or privilege to access the specific resource. Re-authenticating with the same credentials will not change the outcome.
Q19: HTTP 201 Created vs. 204 No Content
Q19: Explain the semantics of HTTP 204 No Content versus 201 Created.

ANSWER:
- 201 Created: Indicates that the request succeeded and resulted in the allocation of a new resource (standard response for POST). It typically returns a Location header directing to the new resource along with the newly created entity in the body.
- 204 No Content: Indicates that the server successfully fulfilled the request, but intentionally returns no message body. Common for DELETE operations or PUT/PATCH updates where the client requires no updated representation.
Q20: 502 Bad Gateway vs. 503 Service Unavailable vs. 504 Gateway Timeout
Q20: What are the differences between HTTP 502 Bad Gateway, 503 Service Unavailable, and 504 Gateway Timeout?

ANSWER:
- 502 Bad Gateway: An edge or proxy server (acting as a gateway) received an invalid, malformed, or dropped response from the upstream application server.
- 503 Service Unavailable: The server is currently unable to handle the request due to temporary overload, resource exhaustion, or scheduled maintenance.
- 504 Gateway Timeout: An edge or proxy server did not receive a timely response from the upstream application/database server within its configured timeout window.
Q21: Content-Type vs. Accept HTTP Headers
Q21: What is the purpose of the Content-Type and Accept HTTP headers?

ANSWER:
- Content-Type: An entity header that informs the receiver about the media type of the sent body content (e.g., Content-Type: application/json or application/xml).
- Accept: A request header where the client specifies the MIME types it can receive and process from the server (e.g., Accept: application/json). Used for content negotiation.
Q22: Path Parameters vs. Query Parameters
Q22: What is the difference between Path Parameters and Query Parameters?

ANSWER:
- Path Parameters: Part of the structural hierarchical URL path, used to identify a specific resource or entity directly:
  https://api.example.com/api/v1/orders/8542 (Identifies Order #8542).
- Query Parameters: Key-value pairs appended after a ? delimiter, used to filter, sort, paginate, or search a collection of resources:
  https://api.example.com/api/v1/orders?status=shipped&limit=20
Q23: CORS Headers & Impact on API Testing
Q23: What are CORS (Cross-Origin Resource Sharing) headers, and why do they impact API testing?

ANSWER:
CORS is a browser security mechanism that restricts web applications from making HTTP requests to a domain different from the one that served the web page.
- Managed via response headers: Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers.
- Impact: Pure backend API testing tools (Postman, REST Assured) ignore CORS because they are not web browsers. However, APIs supporting web frontend applications must return correct CORS headers to avoid blocking in browser clients.
Q24: The Authorization: Bearer Header Format
Q24: What is the Authorization: Bearer header, and what is its standard format?

ANSWER:
Used in token-based authentication (such as OAuth 2.0 and JWT):
Authorization: Bearer <token_string>

The client transmits this header with every authenticated request. The server parses the bearer token, verifies its cryptographic signature, decodes permissions, and processes the call without maintaining server-side session state.
Q25: JSON Web Token (JWT) Architectural Structure
Q25: What is a JSON Web Token (JWT), and what are its three architectural components?

ANSWER:
A JWT is a compact, URL-safe standard (RFC 7519) for transmitting claims between parties:
Base64URL(Header) . Base64URL(Payload) . Signature

1. Header: Identifies the token type (JWT) and signing algorithm (e.g., HMAC SHA256 or RSA).
2. Payload: Contains identity claims, issuer, issue date, expiration time (exp), and assigned roles.
3. Signature: Cryptographic hash produced using the encoded header, encoded payload, and a secret key, ensuring data integrity.
Q26: HTTP ETag Headers & Cache Revalidation
Q26: What is the HTTP ETag header, and how does it support API caching and conditional requests?

ANSWER:
An ETag (Entity Tag) is an identifier assigned by the server to a specific version of a resource (often a hash of the content).
- The client caches the resource and its ETag.
- In subsequent requests, the client sends If-None-Match: "<etag_value>".
- If the resource has not changed, the server returns 304 Not Modified without a body, saving bandwidth.
- For updates, clients use If-Match: "<etag_value>" to prevent the "lost update" problem in concurrent environments.
Q27: Rate Limiting & 429 Status Header Telemetry
Q27: What is API Rate Limiting, and which HTTP status and headers communicate it?

ANSWER:
Rate limiting caps the number of requests a consumer can make within a designated time window.
- Status Code: 429 Too Many Requests.
- Standard Headers:
  - X-RateLimit-Limit: Maximum allowable calls per period.
  - X-RateLimit-Remaining: Remaining calls available in the current window.
  - X-RateLimit-Reset: Time in epoch seconds when the quota refreshes.
  - Retry-After: Number of seconds or timestamp the client must wait before retrying.
Q28: Dynamic Content Negotiation & 406 Errors
Q28: How does Content Negotiation work in an API?

ANSWER:
The client specifies desired formats, languages, or encodings using headers:
- Accept: application/json, application/xml;q=0.9 (Client prefers JSON, accepts XML).
- Accept-Encoding: gzip, deflate, br (Compression algorithm).
- Accept-Language: en-US, fr;q=0.8.
If the server cannot provide the representation requested in the Accept header, it returns 406 Not Acceptable.
Section 3: Tool: Postman & Newman Automation (Q29 – Q45)
Postman script lifecycles, variable scopes, environment extractors, schema validation, Newman CI/CD execution, and mock servers.
Q29: Postman Sandbox Request Execution Lifecycle
Q29: What is the Postman Sandbox execution lifecycle for a single request?

ANSWER:
[Pre-request Script] ➔ [Send Request to Server] ➔ [Receive Response] ➔ [Post-response Tests Script]

1. Pre-request Script: JavaScript executed before the HTTP request is built and sent (used for timestamp generation, hashing, setting dynamic headers, or obtaining tokens).
2. Network Phase: Postman dispatches the HTTP call.
3. Response Received: Server payload and headers are captured.
4. Post-response / Tests Script: JavaScript assertions executed against status code, headers, latency, and response body.
Q30: Postman Variable Scopes Hierarchy
Q30: What are the variable scopes in Postman, ordered from narrowest to broadest?

ANSWER:
1. Data Variables: Read from external data files (CSV/JSON) during Collection Runner executions.
2. Local Variables: Temporarily declared inside scripts (let x = 10), discarded after script execution.
3. Iteration Variables: Defined within the scope of a specific iteration.
4. Request Variables: Assigned directly to a specific request.
5. Folder Variables: Scoped to all requests inside a sub-folder.
6. Collection Variables: Stored across all requests inside a collection.
7. Environment Variables: Bound to an active environment (Dev, QA, Prod).
8. Global Variables: Accessible across all workspaces and collections.
Q31: Token Extraction & Environment Variable Storage
Q31: How do you extract an authentication token from a login response and save it as an environment variable in Postman?

ANSWER:
Inside the Tests tab of the authentication request:
// Parse JSON response
const responseData = pm.response.json();

// Assert token presence
pm.expect(responseData.token).to.not.be.undefined;

// Set environment variable
pm.environment.set("jwt_token", responseData.token);

Subsequent requests reference this variable in headers as:
Authorization: Bearer {{jwt_token}}
Q32: Postman pm.test Assertions (Status, Latency, Nested JSON)
Q32: Write a Postman test script using pm.test to validate status code, response time, and a nested JSON field.

ANSWER:
// Validate Status Code
pm.test("Status code is 200 OK", function () {
    pm.response.to.have.status(200);
});

// Validate Response Time
pm.test("Response time is under 500ms", function () {
    pm.expect(pm.response.responseTime).to.be.below(500);
});

// Validate Nested JSON Properties
pm.test("User billing address city is Pune", function () {
    const data = pm.response.json();
    pm.expect(data.user.billing.city).to.eql("Pune");
});
Q33: JSON Schema Validation in Postman
Q33: How do you perform JSON Schema validation in Postman?

ANSWER:
Using the built-in tv4 or ajv validator library in the Postman Sandbox:
const schema = {
    "type": "object",
    "required": ["id", "username", "isActive"],
    "properties": {
        "id": { "type": "integer" },
        "username": { "type": "string" },
        "isActive": { "type": "boolean" }
    }
};

pm.test("Validate JSON Schema", function () {
    const responseData = pm.response.json();
    pm.expect(tv4.validate(responseData, schema)).to.be.true;
});
Q34: Headless Newman CLI Execution & HTML Reports
Q34: What is Newman, and what is its CLI command to run a collection with an environment and generate HTML reports?

ANSWER:
Newman is the Node.js-based command-line companion runner for Postman. It allows collections to run headlessly in CI/CD pipelines without opening the desktop GUI.
newman run MyCollection.json \
  -e QA_Environment.json \
  -d test_data.csv \
  -r cli,htmlextra \
  --reporter-htmlextra-export ./reports/api_report.html
Q35: Dynamic Workflows via postman.setNextRequest()
Q35: How do you implement dynamic request workflows using postman.setNextRequest()?

ANSWER:
postman.setNextRequest("Request_Name_or_ID") overrides the default linear execution order of collection runners:
const response = pm.response.json();

if (response.status === "PENDING") {
    // Re-poll the same check-status request
    postman.setNextRequest("CheckStatusRequest");
} else if (response.status === "FAILED") {
    // Abort execution or branch to cleanup
    postman.setNextRequest(null); // Terminates collection run
} else {
    // Proceed to process order
    postman.setNextRequest("ProcessOrderRequest");
}
Q36: Data-Driven Testing in Postman Runner
Q36: How do you execute Data-Driven Testing in Postman via Collection Runner?

ANSWER:
1. Create a data.csv or data.json containing test cases:
   [
     {"username": "user1", "expectedRole": "Admin"},
     {"username": "user2", "expectedRole": "Viewer"}
   ]
2. Parameterize request URLs or bodies: {"name": "{{username}}"}.
3. In the Tests tab, reference row data using pm.iterationData.get("expectedRole"):
   pm.test("Verify Role", function() {
       pm.expect(pm.response.json().role).to.eql(pm.iterationData.get("expectedRole"));
   });
4. Load the data file into the Postman Collection Runner or run with Newman (-d data.json).
Q37: Mock Server Provisioning in Postman
Q37: How do you mock an API endpoint directly within Postman?

ANSWER:
1. In Postman, select a collection and click Add Mock Server.
2. Define request routes, methods, and default response bodies.
3. Postman provisions a cloud-hosted URL (e.g., https://<mock-id>.mock.pstmn.io).
4. Save an example response under a request; Postman's matching algorithm matches the incoming path, method, and headers to serve the mock representation.
Q38: Dynamic Mock Data via Faker.js Library
Q38: How do you generate dynamic randomized mock data in Postman request bodies?

ANSWER:
Use Postman's dynamic variables built on the faker.js library:
{
  "customerId": "{{$guid}}",
  "name": "{{$randomFullName}}",
  "email": "{{$randomEmail}}",
  "company": "{{$randomCompanyName}}",
  "timestamp": {{$timestamp}}
}
Q39: Postman Visualizer Integration
Q39: What is the purpose of the Postman Visualizer, and how is it invoked?

ANSWER:
Postman Visualizer renders JSON/XML API response payloads as visual HTML tables, charts, or diagrams inside the Postman response window:
const template = `
    <table border="1">
        <tr><th>User ID</th><th>Email</th></tr>
        {{#each response}}
            <tr><td>{{id}}</td><td>{{email}}</td></tr>
        {{/each}}
    </table>
`;
pm.visualizer.set(template, { response: pm.response.json() });
Q40: Postman Cloud Monitors for Production Uptime
Q40: What are Postman Monitors, and how do they function?

ANSWER:
Postman Monitors run recurring, scheduled cloud-based collection runs (e.g., every 5 minutes or daily) from distributed geographic regions. They monitor production endpoint availability, response latency, and functional contract regressions, notifying teams via email, Slack, or PagerDuty upon assertion failure.
Q41: Programmatic Requests via pm.sendRequest()
Q41: How do you programmatically trigger an external HTTP request from within a Postman Pre-request Script?

ANSWER:
Use pm.sendRequest():
pm.sendRequest({
    url: "https://auth.example.com/oauth/token",
    method: "POST",
    header: "Content-Type:application/x-www-form-urlencoded",
    body: {
        mode: "urlencoded",
        urlencoded: [
            { key: "client_id", value: "app_101" },
            { key: "client_secret", value: "secret_val" },
            { key: "grant_type", value: "client_credentials" }
        ]
    }
}, function (err, res) {
    if (!err) {
        pm.environment.set("bearer_token", res.json().access_token);
    }
});
Q42: Multipart/form-data File Uploads in Postman
Q42: How do you test file upload functionality in Postman?

ANSWER:
1. Create a POST request.
2. Select the Body tab and choose the form-data radio button.
3. Hover over the Key field, switch the dropdown from Text to File.
4. In the Value column, click Select Files and choose a local file (e.g., image.png).
5. Ensure the Content-Type header is managed automatically by Postman to include the multipart/form-data; boundary=... string.
Q43: Response Header & Cookie Assertions
Q43: How do you assert response headers and cookies in Postman?

ANSWER:
// Validate Header
pm.test("Header verification", function () {
    pm.response.to.have.header("Content-Type", "application/json; charset=utf-8");
});

// Validate Cookie
pm.test("Session cookie is present", function () {
    pm.expect(pm.cookies.has("session_id")).to.be.true;
    pm.expect(pm.cookies.get("session_id")).to.match(/^[a-f0-9]{32}$/);
});
Q44: Postman Enterprise Scaling Limitations
Q44: What are the limitations of Postman for enterprise API testing?

ANSWER:
- High memory consumption when running large collections in GUI mode.
- Difficult merge conflict resolution when collaborating via Git repositories (Postman exports monolithic JSON files).
- Limited multi-threaded, high-concurrency load and performance testing capabilities.
- Limited integration for testing lower-level protocols (e.g., binary TCP, custom gRPC streaming, AMQP message queues).
Q45: Newman Pipeline Integration with Jenkins
Q45: How can Newman be integrated into a Jenkins CI/CD pipeline?

ANSWER:
pipeline {
    agent any
    stages {
        stage('Install Newman') {
            steps {
                sh 'npm install -g newman newman-reporter-htmlextra'
            }
        }
        stage('Execute API Tests') {
            steps {
                sh 'newman run collections/api_suite.json -e env/qa.json -r cli,htmlextra --reporter-htmlextra-export reports/test_report.html'
            }
        }
    }
    post {
        always {
            publishHTML([target: [reportDir: 'reports', reportFiles: 'test_report.html', reportName: 'API Report']])
        }
    }
}
Section 4: Tool: REST Assured (Java Framework) (Q46 – Q60)
BDD Given-When-Then DSL, Request/Response specifications, GPath evaluations, POJO serialization/deserialization, and TestNG integration.
Q46: Given-When-Then BDD Domain Specific Language
Q46: What is REST Assured, and what syntax structure does it use?

ANSWER:
REST Assured is an open-source Java library specifically designed to simplify the automation, validation, and testing of RESTful APIs over HTTP. It uses a domain-specific language (DSL) based on the BDD (Behavior-Driven Development) Given-When-Then syntax:
- given(): Sets up preconditions (headers, parameters, authentication, cookies, request body).
- when(): Triggers the HTTP action (get(), post(), put(), delete()).
- then(): Asserts and validates the response (status code, body attributes, headers).
Q47: Basic REST Assured Test with Hamcrest Matchers
Q47: Write a basic REST Assured test verifying a GET endpoint status code and response payload.

ANSWER:
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
import org.testng.annotations.Test;

public class ApiTest {
    @Test
    public void verifyUserEndpoint() {
        given()
            .baseUri("https://reqres.in")
            .header("Content-Type", "application/json")
        .when()
            .get("/api/users/2")
        .then()
            .statusCode(200)
            .body("data.first_name", equalTo("Janet"))
            .body("data.id", equalTo(2));
    }
}
Q48: RequestSpecification & ResponseSpecification Builders
Q48: How do you configure RequestSpecification and ResponseSpecification to eliminate code redundancy in REST Assured?

ANSWER:
RequestSpecification reqSpec = new RequestSpecBuilder()
    .setBaseUri("https://api.example.com")
    .setContentType(ContentType.JSON)
    .addHeader("Authorization", "Bearer my_token")
    .build();

ResponseSpecification resSpec = new ResponseSpecBuilder()
    .expectStatusCode(200)
    .expectContentType(ContentType.JSON)
    .expectResponseTime(lessThan(2000L))
    .build();

// Usage in tests
given().spec(reqSpec).when().get("/users").then().spec(resSpec);
Q49: GPath Groovy Path Expressions in REST Assured
Q49: What is GPath in REST Assured, and how is it used to query JSON responses?

ANSWER:
REST Assured uses Groovy's GPath notation to traverse and query complex nested JSON and XML data.
// Extracting titles of all books priced under 10
List<String> cheapBooks = given()
    .when().get("/store")
    .then().extract().path("store.book.findAll { it.price < 10 }.title");
Q50: POJO Serialization & Deserialization via Jackson
Q50: How do you serialize a Java POJO into a JSON request body and deserialize the response back to a POJO?

ANSWER:
Using serialization libraries (Jackson or Gson) configured on the classpath:
// POJO
public class User {
    private String name;
    private String job;
    // constructors, getters, setters
}

// Serialization (POJO -> JSON)
User userPayload = new User("Rahul", "SDET");
User createdUser = given()
    .contentType(ContentType.JSON)
    .body(userPayload)
.when()
    .post("/api/users")
// Deserialization (JSON -> POJO)
.then()
    .statusCode(201)
    .extract().as(User.class);

assert createdUser.getName().equals("Rahul");
Q51: JSON Schema Validation in REST Assured
Q51: How do you perform JSON Schema validation in REST Assured?

ANSWER:
Include the json-schema-validator dependency and use Hamcrest matchers:
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;

given()
.when()
    .get("/api/users/2")
.then()
    .assertThat()
    .body(matchesJsonSchemaInClasspath("user_schema.json"));
Q52: Chaining Endpoints with Extracted Path Parameters
Q52: How do you extract and pass values between chained API requests in REST Assured?

ANSWER:
// Step 1: Create user and extract generated ID
int userId = given()
    .contentType(ContentType.JSON)
    .body("{\"name\": \"Anita\", \"role\": \"QA\"}")
.when()
    .post("/api/users")
.then()
    .statusCode(201)
    .extract().path("id");

// Step 2: Use extracted ID in subsequent GET request
given()
    .pathParam("id", userId)
.when()
    .get("/api/users/{id}")
.then()
    .statusCode(200)
    .body("name", equalTo("Anita"));
Q53: Multipart File Upload Operations
Q53: How do you handle file uploads in REST Assured using multiPart()?

ANSWER:
File fileToUpload = new File("src/test/resources/sample.pdf");

given()
    .multiPart("file", fileToUpload)
    .multiPart("description", "Invoice document")
.when()
    .post("/api/upload")
.then()
    .statusCode(200)
    .body("status", equalTo("SUCCESS"));
Q54: Basic, Preemptive & Bearer Authentication
Q54: How do you configure Basic Authentication, Preemptive Authentication, and Bearer Tokens in REST Assured?

ANSWER:
// Basic Auth (standard challenge-response)
given().auth().basic("username", "password");

// Preemptive Basic Auth (sends credentials in initial header)
given().auth().preemptive().basic("username", "password");

// Bearer Token
given().auth().oauth2("access_token_value");
// Or manually via header:
given().header("Authorization", "Bearer " + token);
Q55: Conditional Logging on Validation Failures
Q55: How do you log request and response details in REST Assured only when an assertion fails?

ANSWER:
Use .log().ifValidationFails():
given()
    .log().ifValidationFails()
    .contentType(ContentType.JSON)
.when()
    .get("/api/users/999")
.then()
    .log().ifValidationFails()
    .statusCode(200); // Prints full request and response to console if status != 200
Q56: Relaxed HTTPS SSL Verification
Q56: How do you bypass SSL/TLS certificate validation errors in REST Assured?

ANSWER:
Use .relaxedHTTPSValidation():
given()
    .relaxedHTTPSValidation() // Ignores self-signed or invalid SSL certificates
.when()
    .get("https://self-signed.badssl.com/")
.then()
    .statusCode(200);
Q57: Latency & Response Time Assertions
Q57: How do you measure and assert API response time in REST Assured?

ANSWER:
Use Hamcrest time matchers:
import static org.hamcrest.Matchers.lessThan;

given()
.when()
    .get("/api/products")
.then()
    .time(lessThan(1500L)); // Asserts response latency is under 1500 milliseconds
Q58: Sending & Extracting Response Cookies
Q58: How do you handle cookies in REST Assured?

ANSWER:
// Sending cookies
given()
    .cookie("session_token", "abc123xyz")
.when()
    .get("/dashboard");

// Extracting response cookies
Response response = get("/login");
String sessionCookie = response.getCookie("session_token");
Map<String, String> allCookies = response.getCookies();
Q59: RootPath Simplification for Deeply Nested Objects
Q59: What is the purpose of the RootPath method in REST Assured?

ANSWER:
Reduces duplication when asserting multiple nested properties within the same parent node:
given().when().get("/company").then()
    .rootPath("company.departments.engineering")
    .body("lead", equalTo("Vikram"))
    .body("headcount", equalTo(45))
    .detachRootPath("departments.engineering"); // Resets root path
Q60: Concurrent Multi-Threaded Execution via TestNG
Q60: How do you run REST Assured test suites concurrently using TestNG?

ANSWER:
In testng.xml, configure parallel test execution:
<suite name="API Suite" parallel="methods" thread-count="4">
  <test name="REST Assured Parallel Tests">
    <classes>
      <class name="com.automation.tests.UserApiTests"/>
      <class name="com.automation.tests.OrderApiTests"/>
    </classes>
  </test>
</suite>
Section 5: Tool: Python API Automation (Requests & PyTest) (Q61 – Q72)
Python requests architecture, session pooling, PyTest fixtures, schema validation, mocks, and Allure reporting.
Q61: Python Requests Architecture & Key Features
Q61: What is the Python requests library, and what are its key features?

ANSWER:
requests is an HTTP library for Python designed for simplicity and readability. Key features include:
- Built-in JSON decoding via response.json()
- Persistent session management (requests.Session()) preserving cookies across calls
- Connection pooling
- Automatic content decompression (gzip, deflate)
- Custom authentication handlers and SSL certificate verification
Q62: PyTest POST Test Case Implementation
Q62: Write a PyTest test case that executes a POST request and validates the response status code and JSON payload.

ANSWER:
import requests
import pytest

def test_create_user():
    url = "https://reqres.in/api/users"
    payload = {"name": "Siddharth", "job": "Data Engineer"}
    headers = {"Content-Type": "application/json"}

    response = requests.post(url, json=payload, headers=headers)

    assert response.status_code == 201
    json_data = response.json()
    assert json_data["name"] == "Siddharth"
    assert "id" in json_data
Q63: data= vs. json= Parameter Serialization
Q63: What is the difference between data= and json= arguments in requests.post()?

ANSWER:
- json=payload: Automatically serializes the Python dictionary into a JSON string and sets the header Content-Type: application/json.
- data=payload: If passed a dictionary, serializes it as form-encoded data (application/x-www-form-urlencoded). If passed a string, transmits raw text without automatically adding the application/json header.
Q64: requests.Session() Connection Pooling & State
Q64: How does requests.Session() optimize API test automation?

ANSWER:
1. Performance: Reuses the underlying TCP socket connection across multiple requests to the same host (HTTP Keep-Alive), reducing connection overhead.
2. State Management: Automatically stores and reapplies cookies received from the server to subsequent requests.
3. Configuration Inheritance: Applies shared headers, base parameters, and authentication to all calls made through the session:
session = requests.Session()
session.headers.update({"Authorization": "Bearer token_123"})
session.get("https://api.example.com/profile")
Q65: Python jsonschema Contract Validation
Q65: How do you implement JSON Schema validation in Python using jsonschema?

ANSWER:
import requests
from jsonschema import validate, ValidationError

def test_validate_schema():
    schema = {
        "type": "object",
        "required": ["id", "title"],
        "properties": {
            "id": {"type": "number"},
            "title": {"type": "string"}
        }
    }
    response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
    try:
        validate(instance=response.json(), schema=schema)
    except ValidationError as e:
        pytest.fail(f"Schema validation failed: {e.message}")
Q66: Data-Driven Parameterization via @pytest.mark.parametrize
Q66: How do you parameterize API tests in PyTest with multiple input datasets?

ANSWER:
Use the @pytest.mark.parametrize decorator:
import pytest
import requests

@pytest.mark.parametrize("user_id, expected_name", [
    (1, "Leanne Graham"),
    (2, "Ervin Howell"),
    (3, "Clementine Bauch")
])
def test_user_names(user_id, expected_name):
    url = f"https://jsonplaceholder.typicode.com/users/{user_id}"
    response = requests.get(url)
    assert response.status_code == 200
    assert response.json()["name"] == expected_name
Q67: Connect/Read Timeouts & Exception Trapping
Q67: How do you handle API request timeouts and handle exceptions in Python?

ANSWER:
Set the timeout parameter (in seconds) to prevent tests from hanging:
import requests
from requests.exceptions import Timeout, ConnectionError

try:
    response = requests.get("https://api.example.com/data", timeout=(3.05, 10))
    # (connect timeout: 3.05s, read timeout: 10s)
except Timeout:
    pytest.fail("Request timed out")
except ConnectionError:
    pytest.fail("Network connection failed")
Q68: PyTest Session Fixture & Teardown Lifecycle
Q68: How do you create reusable PyTest fixtures for API authentication and teardown in conftest.py?

ANSWER:
# conftest.py
import pytest
import requests

@pytest.fixture(scope="session")
def auth_session():
    session = requests.Session()
    login_url = "https://api.example.com/auth/login"
    res = session.post(login_url, json={"user": "admin", "pass": "secret"})
    token = res.json()["access_token"]
    session.headers.update({"Authorization": f"Bearer {token}"})
    
    yield session  # Provides session to test functions
    
    # Teardown logic
    session.post("https://api.example.com/auth/logout")
    session.close()
Q69: Binary File Stream Uploads in Python
Q69: How do you upload a file using the Python requests library?

ANSWER:
Use the files parameter:
url = "https://api.example.com/upload"
files = {'document': open('report.pdf', 'rb')}
data = {'user_id': '101'}

response = requests.post(url, files=files, data=data)
assert response.status_code == 200
Q70: Mocking Outbound Calls with responses Library
Q70: How do you mock external API calls in PyTest using responses or unittest.mock?

ANSWER:
Using the responses library:
import responses
import requests

@responses.activate
def test_mock_api():
    # Define mock response
    responses.add(
        responses.GET,
        "https://api.payment.com/checkout/1",
        json={"status": "PAID", "amount": 499},
        status=200
    )
    
    # Function under test makes request
    res = requests.get("https://api.payment.com/checkout/1")
    assert res.status_code == 200
    assert res.json()["status"] == "PAID"
Q71: Header Traversal & Security Header Checks
Q71: How do you capture and assert specific HTTP response headers in Python?

ANSWER:
response = requests.get("https://api.example.com/items")
assert "application/json" in response.headers["Content-Type"]
assert response.headers.get("X-Frame-Options") == "DENY"
Q72: Allure and PyTest HTML Reporting
Q72: How do you generate HTML and Allure test reports with PyTest for API tests?

ANSWER:
# Using pytest-html
pytest --html=reports/api_report.html --self-contained-html

# Using Allure-PyTest
pytest --alluredir=./allure-results
allure serve ./allure-results
Section 6: Tool: SoapUI & Web Services Testing (Q73 – Q82)
WSDL inspection, SOAP Envelope mechanics, Fault handling, XPath/XQuery assertions, Groovy test scripts, and WS-Security.
Q73: SoapUI Architecture & Core Test Capabilities
Q73: What is SoapUI, and what are its primary testing capabilities?

ANSWER:
SoapUI is an API testing tool designed for SOAP and REST web services. Key capabilities include:
- Parsing WSDL files to auto-generate request templates
- Validating complex XML messages against XSD schemas
- Functional testing, test assertions, and test step chaining
- API virtualization and service mocking
- Automated WS-Security injection (signatures, timestamps, encryption)
Q74: WSDL XML Schema Structure & Tags
Q74: What is a WSDL (Web Services Description Language) file, and what are its primary structural tags?

ANSWER:
A WSDL file is an XML document describing the interface, location, and operations of a SOAP web service.
- <types>: Data type definitions used in messages (typically XSD schemas).
- <message>: Abstract description of data transmitted (input parameters, output return types).
- <portType>: Set of operations exposed by the service (similar to an interface in OOP).
- <binding>: Concrete protocol specifications (e.g., SOAP over HTTP).
- <service>: Physical deployment location/URL endpoint of the service.
Q75: SOAP Message Envelope XML Architecture
Q75: Explain the structure of a SOAP Message Envelope.

ANSWER:
<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Header>
        <!-- Optional authentication, routing, and transaction metadata -->
    </soap:Header>
    <soap:Body>
        <!-- Mandatory XML payload / operation call -->
        <m:GetStockPrice xmlns:m="https://stocks.example.com">
            <m:StockSymbol>INFY</m:StockSymbol>
        </m:GetStockPrice>
        <!-- Optional soap:Fault block here if errors occurred -->
    </soap:Body>
</soap:Envelope>
Q76: SOAP Fault Sub-Elements & Error Propagation
Q76: What is a SOAP Fault, and what sub-elements does it contain?

ANSWER:
A SOAP Fault is a standardized XML block returned inside <soap:Body> when an error occurs during message processing:
- <faultcode>: Code identifying error category (e.g., VersionMismatch, MustUnderstand, Client, Server).
- <faultstring>: Human-readable error description.
- <faultactor>: Identifies which system in the transmission chain caused the fault.
- <detail>: Application-specific error information or stack traces.
Q77: SoapUI Standard Assertion Inventory
Q77: What are the primary assertion types used in SoapUI?

ANSWER:
1. Schema Compliance: Validates that the response message conforms to the WSDL/XSD definition.
2. SOAP Fault / Not SOAP Fault: Verifies whether the server returned a fault envelope.
3. XPath Match: Uses XPath expressions to evaluate specific XML node values.
4. XQuery Match: Queries and compares complex XML subtrees.
5. Contains / Not Contains: Regular expression and substring matching.
6. Response SLA: Validates that response time falls within acceptable latency limits.
Q78: XPath Match Assertions with Namespaces
Q78: How do you assert a specific XML tag value in SoapUI using an XPath Match assertion?

ANSWER:
// Declare namespace
declare namespace ns='https://banking.example.com/accounts';
// XPath to element
//ns:AccountResponse[1]/ns:Balance[1]

Expected Value: 50000.00
Q79: Property Transfer Mechanics for Chained Steps
Q79: What is Property Transfer in SoapUI, and how does it support test step chaining?

ANSWER:
The Property Transfer test step extracts a dynamic value from the response of an earlier test step (via XPath or JSONPath) and writes it into a property or input field of a downstream request (e.g., transferring a generated SessionID from a Login request into a Payment request).
Q80: Groovy Scripting for Dynamic Assertions in SoapUI
Q80: How do you execute Groovy scripts in SoapUI for custom assertions and test automation?

ANSWER:
Add a Groovy Script test step:
// Read response from preceding step
def response = testRunner.testCase.getTestStepByName("GetUserInfo").getPropertyValue("response")

// Parse XML
def xml = new XmlSlurper().parseText(response)
assert xml.Body.UserResponse.Status.text() == "ACTIVE"

// Dynamically update a global context property
testRunner.testCase.testSuite.setPropertyValue("GlobalUserID", xml.Body.UserResponse.ID.text())
Q81: WS-Security (XML Signature & Encryption)
Q81: What is WS-Security (Web Services Security) in SOAP services, and how is it tested?

ANSWER:
WS-Security is an OASIS standard that applies security mechanisms directly at the message layer:
- XML Signature: Cryptographically signs parts of the SOAP message for data integrity and non-repudiation.
- XML Encryption: Encrypts specific XML nodes within <soap:Body> so intermediaries cannot read sensitive fields.
- Security Tokens: Embeds UsernameTokens, Kerberos tickets, or X.509 certificates inside <soap:Header>.
SoapUI tests WS-Security by configuring keystores and adding WS-Security configurations directly to project endpoints.
Q82: Headless Command-Line Execution via testrunner
Q82: How do you run SoapUI test cases from a CI/CD command line?

ANSWER:
Using the bundled testrunner.bat (Windows) or testrunner.sh (Linux) command-line utility:
./testrunner.sh -s"SmokeTestSuite" -c"UserVerificationTestCase" -r -a -f/reports/soapui "MySoapUIProject.xml"
Section 7: Performance & Security Testing Tools (JMeter & OWASP ZAP) (Q83 – Q92)
Load simulation in JMeter, JSON extractors, TPS/Percentile metrics, OWASP API Top 10 vulnerabilities, and automated ZAP scans.
Q83: Configuring JMeter HTTP API Samplers
Q83: How do you configure an HTTP API request in Apache JMeter?

ANSWER:
1. Create a Test Plan.
2. Add a Thread Group (configure Number of Threads/Users, Ramp-up Period, Loop Count).
3. Add an HTTP Request Sampler:
   - Set Method (GET, POST, etc.)
   - Set Server Name/IP and Port
   - Set Path (/api/v1/orders)
4. Add an HTTP Header Manager child element to inject Content-Type: application/json and Authorization: Bearer <token>.
5. Add a View Results Tree or Summary Report listener to capture output.
Q84: Dynamic Correlation with JMeter JSON Extractor
Q84: How do you perform parameter extraction and correlation in JMeter for APIs?

ANSWER:
Use the JSON Extractor post-processor attached to an HTTP Sampler:
- Name of created variable: extractedToken
- JSON Path expression: $.auth.access_token
- Match No.: 1
- Default Value: NOT_FOUND

Subsequent HTTP samplers reference this variable as: ${extractedToken}.
Q85: Core API Performance Metrics (TPS, Latency, Percentiles)
Q85: What are the key performance metrics evaluated during API Load Testing?

ANSWER:
- Throughput (TPS / RPS): Transactions/Requests executed per second.
- Latency (Response Time): Time from sending the request until the first byte arrives.
- Elapsed Time (Total Duration): Time taken to complete the full request and receive the final byte.
- Percentiles (p90, p95, p99): Latency threshold beneath which 90%, 95%, or 99% of requests resolve.
- Error Rate: Percentage of requests returning 5xx or unexpected 4xx errors under load.
Q86: Headless Non-GUI JMeter CLI Execution
Q86: How do you execute API performance tests in JMeter without the resource-heavy GUI?

ANSWER:
Always execute load tests via JMeter CLI mode:
jmeter -n -t ApiLoadTest.jmx -l results.jtl -e -o ./HtmlDashboardReport/

- -n: Non-GUI mode
- -t: Test plan JMX file
- -l: Log file path for raw sample results
- -e -o: Generates interactive HTML dashboard reports upon test completion
Q87: OWASP API Security Top 10 Taxonomy
Q87: What are the OWASP API Security Top 10 vulnerabilities?

ANSWER:
1. API1: Broken Object Level Authorization (BOLA/IDOR): Endpoints accept user-supplied IDs to manipulate records without verifying user ownership.
2. API2: Broken Authentication: Flawed token issuance, credential stuffing, or missing signature validation.
3. API3: Broken Object Property Level Authorization: Exposing sensitive fields via Mass Assignment or excessive data exposure.
4. API4: Unrestricted Resource Consumption: Missing rate limits, execution timeouts, or payload memory caps.
5. API5: Broken Function Level Authorization (BFLA): Regular users executing administrative API methods.
6. API6: Unrestricted Access to Sensitive Business Flows: Automated abuse of critical functions (e.g., ticket scalping).
7. API7: Server-Side Request Forgery (SSRF): Forcing the API server to query internal network locations.
8. API8: Security Misconfiguration: Missing CORS policies, unpatched servers, verbose error traces.
9. API9: Improper Inventory Management: Exposed legacy (v1), debug, or shadow APIs.
10. API10: Unsafe Consumption of APIs: Trusting third-party API data without sanitization.
Q88: Broken Object Level Authorization (BOLA/IDOR) Testing
Q88: What is Broken Object Level Authorization (BOLA / IDOR), and how do you test for it?

ANSWER:
BOLA occurs when an API endpoint takes an object identifier (/api/accounts/1042/statement) without validating whether the requesting user owns that account.
Testing Strategy:
1. Authenticate as User A, create a private resource, and note the Resource ID (1042).
2. Authenticate as User B and obtain User B's valid authorization token.
3. Send an HTTP GET or DELETE to /api/accounts/1042/statement using User B's token.
4. If the server returns 200 OK instead of 403 Forbidden or 404 Not Found, a BOLA vulnerability exists.
Q89: Mass Assignment Vulnerability Probing
Q89: How do you test for Mass Assignment (Broken Object Property Level Authorization)?

ANSWER:
Mass assignment happens when frameworks automatically bind incoming JSON payload keys directly to internal database entity fields.
Testing Strategy:
Submit extra parameters in a registration or profile update payload:
{
  "username": "student",
  "password": "Password123",
  "is_admin": true,
  "account_balance": 999999
}

If the user gains admin privileges, the API is vulnerable to mass assignment.
Q90: OWASP ZAP Automated OpenAPI Security Auditing
Q90: How do you automate API vulnerability scanning using OWASP ZAP (Zed Attack Proxy)?

ANSWER:
1. Import the API definition into ZAP via the OpenAPI / Swagger add-on.
2. Configure Authentication Script to ensure ZAP attaches active session headers.
3. Run the Active Scanner, which dispatches payloads targeting SQL Injection, XSS, Path Traversal, and Header Injections.
4. Generate reports or integrate into CI pipelines via the ZAP baseline Docker container:
docker run -v $(pwd):/zap/wrk/:rw -t ghcr.io/zaproxy/zaproxy:stable zap-api-scan.py \
  -t https://api.example.com/swagger.json -f openapi -r zap_report.html
Q91: SQL Injection (SQLi) Identification via APIs
Q91: What is SQL Injection (SQLi) in the context of APIs, and how is it detected?

ANSWER:
SQLi occurs when untrusted input parameters (from query strings, path variables, or JSON bodies) are concatenated directly into dynamic SQL queries without parameterized validation.
Detection: Submit payloads like ' OR '1'='1' -- or 1; WAITFOR DELAY '0:0:5'--. Inspect whether the API reveals SQL syntax error details (e.g., PostgreSQL/MySQL traces) or displays measurable time delays (Time-based Blind SQLi).
Q92: API Fuzz Testing Principles
Q92: What is API Fuzz Testing?

ANSWER:
Fuzz testing (fuzzing) involves bombarding API endpoints with high volumes of invalid, malformed, unexpected, or boundary-breaking inputs (e.g., non-printable characters, extremely large strings, unexpected data types, SQL/XSS tokens) to identify unhandled exceptions, memory leaks, and buffer overflows.
Section 8: Advanced Frameworks, Mocking & CI/CD (Q93 – Q100)
Karate DSL, WireMock service virtualization, Pact consumer-driven contracts, Webhooks, Playwright API testing, and legacy reverse-engineering.
Q93: Karate Framework vs. REST Assured
Q93: What is Karate Framework, and what makes it distinct from REST Assured?

ANSWER:
Karate is an open-source test automation framework built on top of Cucumber's Gherkin syntax.
Distinction: Unlike REST Assured (which requires Java code, POJO creation, and compilation), Karate tests are written directly in plain-text .feature files without writing boilerplate Java code:
Feature: User Verification
Scenario: Fetch user and assert status
  Given url 'https://reqres.in/api/users/2'
  When method get
  Then status 200
  And match response.data.first_name == 'Janet'

Native support for JSON/XML payload matching, mocking, and parallel execution.
Q94: WireMock Virtualization & Latency Injection
Q94: What is WireMock, and how is it used in API testing?

ANSWER:
WireMock is a library and standalone server used for mocking and virtualizing HTTP-based APIs. It acts as an integration-testing service that simulates external third-party dependencies (payment gateways, legacy backends).
// Stubbing a WireMock endpoint
stubFor(get(urlEqualTo("/api/credit-score/101"))
    .willReturn(aResponse()
        .withStatus(200)
        .withHeader("Content-Type", "application/json")
        .withBody("{\"score\": 750, \"status\": \"APPROVED\"}")
        .withFixedDelay(200))); // Simulates network latency
Q95: Pact Consumer-Driven Contract Verification
Q95: What is Consumer-Driven Contract Testing, and how does Pact work?

ANSWER:
In Consumer-Driven Contract Testing, the Consumer service writes unit tests defining the exact request payloads it sends and the minimal response attributes it requires from the Provider.
1. Pact generates a local JSON "Pact contract" file during consumer unit test execution.
2. The contract file is uploaded to an enterprise Pact Broker.
3. During the Provider's CI build, the Provider downloads the contract, runs mock calls against its own endpoints, and verifies that its responses satisfy the consumer's expectations.
4. Ensures services can deploy independently without breaking dependent consumers.
Q96: Asynchronous Webhook Verification Strategies
Q96: What is a Webhook, and how do you test asynchronous Webhook deliveries?

ANSWER:
A webhook is a "reverse API" where the server pushes real-time events to an external client endpoint via an HTTP POST request immediately upon an event occurring (event-driven architecture).
Testing Strategy:
1. Provision a transient, public webhook receiver (e.g., using Beeceptor, Webhook.site, or local WireMock servers exposed via ngrok).
2. Register the callback receiver URL with the provider service under test.
3. Trigger the business event (e.g., finalize an order).
4. Assert that the provider delivered an HTTP POST to the receiver containing the expected payload and HMAC signature header within an acceptable timeframe.
Q97: Headless API Automation with Playwright
Q97: How do you perform API testing using Playwright?

ANSWER:
Playwright includes native support for headless API testing via its APIRequestContext interface without needing a browser:
from playwright.sync_api import sync_playwright

def test_playwright_api():
    with sync_playwright() as p:
        request_context = p.request.new_context(base_url="https://reqres.in")
        response = request_context.get("/api/users/2")
        
        assert response.status == 200
        data = response.json()
        assert data["data"]["first_name"] == "Janet"
        request_context.dispose()
Q98: Cypress API Testing Architecture & Bottlenecks
Q98: What is Cypress API Testing, and what is its primary limitation?

ANSWER:
Cypress executes API requests directly using cy.request():
cy.request('GET', 'https://api.example.com/users').then((response) => {
    expect(response.status).to.eq(200);
    expect(response.body).to.have.length.greaterThan(0);
});

Limitation: Cypress runs inside the browser sandbox; it does not natively support multi-threaded backend load tests, non-HTTP protocols, or multiple concurrent background threads.
Q99: Enterprise API Automation Framework Architecture
Q99: How do you design an enterprise-grade automated API Testing Framework from scratch?

ANSWER:
An enterprise API testing framework incorporates:
1. Core HTTP Client: REST Assured (Java) or Requests (Python).
2. Test Runner: TestNG / JUnit5 (Java) or PyTest (Python) for test execution, tagging, and parallelization.
3. Configuration & Data Layer: Externalized configuration (environments, base URLs) using .properties, .yaml, and test data managers (JSON/Excel).
4. Serialization Engine: Jackson/Gson for POJO mapping.
5. Reporting: Allure Reports or ExtentReports capturing detailed request/response payloads on failure.
6. Validation Engine: AssertJ / Hamcrest and JSON Schema Validators.
7. CI/CD Integration: Containerized Dockerfile running headless via GitHub Actions, GitLab CI, or Jenkins.
Q100: Reverse-Engineering & Probing Undocumented APIs
Q100: What strategies should be followed to test legacy APIs that lack documentation?

ANSWER:
1. Traffic Sniffing & Proxy Analysis: Intercept live client-server network traffic using debugging proxies like OWASP ZAP, Fiddler, or Charles Proxy to capture URLs, methods, headers, and request/response payloads.
2. Reverse Engineer Schemas: Ingest captured traffic into Postman or tools like mitmproxy2swagger to auto-generate baseline OpenAPI/Swagger specs.
3. Equivalence Partitioning & Boundary Value Analysis (BVA): Probe endpoints systematically with diverse data types (strings, nulls, negative numbers, large inputs) to determine input constraints.
4. Analyze Database State: Monitor internal database mutations directly before and after executing POST, PUT, and DELETE requests to verify functional behavior and side-effects.