API Testing Interview Questions And Answers

Last Updated : 20 Jul, 2026

API testing verifies whether APIs exchange data correctly and respond as expected between different software systems. It helps ensure stable communication, faster performance, and secure backend operations in modern applications.

  • Validates API requests, responses, and data transfer.
  • Helps detect backend issues before UI-level failures occur.
  • Improves software reliability, security, and system integration.

API Testing Interview Questions For Freshers

These questions focus on foundational concepts to help freshers build a strong understanding of API testing basics.

1. What is API testing, and why is it important?

API Testing is a software testing technique that verifies whether an Application Programming Interface (API) functions correctly, securely, reliably, and efficiently by testing requests, responses, and business logic without using the user interface.

  • Detects defects early in the development cycle, reducing the cost of fixing bugs.
  • Validates business logic and ensures accurate request-response processing.
  • Ensures seamless communication between applications, services, and databases.
API-testing-process
API testing process

2. What is an API and Types of APIs?

An Application Programming Interface (API) is a set of rules and protocols that allows different software applications to communicate and exchange data with each other. It acts as an intermediary between two systems, enabling them to interact without exposing their internal implementation.

frame_3258
API

Types of APIs

  • Web APIs: Communicate over HTTP/HTTPS (REST, SOAP, GraphQL).
  • Local APIs: Used between applications on the same system.
  • Remote APIs: Communicate between different systems over a network.
  • Library/Framework APIs: APIs provided by programming libraries or frameworks.

3. What is an Endpoint in API Testing?

An API endpoint is a specific URL (Uniform Resource Locator) where an API can be accessed to perform a particular operation or retrieve a resource. It acts as the communication point between the client and the server, allowing requests to be sent and responses to be received.

Example: https://api.example.com/users/101

Here, /users/101 is the endpoint used to retrieve details of the user with ID 101.

client
endpoint in API

4. What is the Purpose of Authentication in API Testing?

API authentication is the process of verifying the identity of a user or system before allowing access to an API. It helps protect secure data and resources from unauthorized access.

  • Verifies the identity of the requester before granting access
  • Improves API security and protects sensitive information
  • Common methods include API Keys, OAuth, JWT, and Basic Authentication
image
API authentication

5. What is the Difference Between REST and SOAP APIs?

REST (Representational State Transfer) and SOAP (Simple Object Access Protocol) are two popular approaches for building web services. REST is a lightweight architectural style that primarily uses HTTP and JSON, while SOAP is a protocol that uses XML with strict messaging standards for secure and reliable communication.

REST APISOAP API
Architectural styleCommunication protocol
Uses HTTP methods (GET, POST, PUT, DELETE, PATCH)Uses XML-based messaging over HTTP, SMTP, TCP, etc.
Supports JSON, XML, and other formatsSupports only XML
Lightweight and fasterHeavier and comparatively slower
Easy to develop, test, and maintainMore complex due to strict standards
Stateless by designCan be stateless or stateful
Widely used for web, mobile, and microservicesCommonly used in enterprise, banking, and legacy systems
Lower bandwidth consumptionHigher bandwidth consumption due to XML

6. Mention Common HTTP Methods used in API Testing.

Here are the Common HTTP Methods of API Testing.

  • GET: Retrieves data or resources from the server without modifying them.
  • POST: Creates a new resource by sending data to the server.
  • PUT: Updates or replaces an existing resource with new data.
  • PATCH: Partially updates specific fields of an existing resource.
  • DELETE: Removes a specified resource from the server.
  • HEAD: Retrieves only the response headers without the response body, mainly used for validation and metadata checks.
  • OPTIONS: Returns the HTTP methods and communication options supported by an API endpoint.

7. What are the Different Types of API Testing?

Here are the different types of API testing:

  • Functional Testing: Checks if the API functions correctly according to the requirements.
  • Load Testing: Tests how the API performs under heavy load or many simultaneous requests to check its stability and responsiveness.
  • Security Testing: Ensures the API is protected against threats like unauthorized access, injection attacks, and data leaks.
  • Reliability Testing: Verifies that the API can handle requests consistently over time without failures.
  • Validation Testing: Confirms that the API returns the expected results and follows the correct data format and protocols.
  • Error Handling Testing: Checks how the API responds to invalid inputs or unexpected conditions, making sure it handles errors gracefully.
  • Interoperability Testing: Ensures the API works well across different devices, platforms, or systems that interact with it.
  • Documentation Testing: Reviews the API documentation to ensure it is accurate, complete, and easy to understand for developers.

8. What is the role of Postman in API testing?

Postman is a popular API testing tool used to design, send, test, and automate API requests. It enables testers and developers to validate API functionality, analyze responses, automate test cases, and collaborate efficiently throughout the API development lifecycle.

9. List the differences between API and Web Service.

Here are the differences between APIs and Web Services:

ParametersAPIWeb Service
DefinitionAn API enables communication between applications.A Web Service is an API accessible over a network.
Protocol SupportCan use HTTP, HTTPS, TCP, WebSockets, etc.Mostly uses HTTP/HTTPS protocols.
Data FormatSupports JSON, XML, YAML, etc.Primarily XML (SOAP) or JSON (REST).

10. What protocols can be tested using API Testing?

API Testing supports various communication protocols that enable data exchange between clients and servers. The choice of protocol depends on the application's architecture, performance, security, and integration requirements.

  • HTTP: Transfers API requests and responses over the web.
  • HTTPS: Encrypts API communication using SSL/TLS.
  • REST: Builds lightweight and scalable APIs using HTTP/HTTPS.
  • SOAP: Uses XML for secure and standardized web service communication.
  • GraphQL: Retrieves only the required data through a single query.
  • gRPC: Enables high-performance communication using HTTP/2 and Protocol Buffers.
  • WebSocket: Supports real-time, bidirectional communication between clients and servers.

11. Tell me Advantages and Limitations of API Testing.

Advantages of API Testing

  • Detects defects early in the development lifecycle.
  • Executes faster than UI testing.
  • Supports automation and CI/CD integration.

Limitations of API Testing

  • Requires knowledge of API protocols and request formats.
  • Cannot validate the user interface or user experience.
  • Complex APIs may require advanced scripting and automation skills.

12. List the differences between API Testing and Unit Testing.

Here is the Differences between API Testing Vs. Unit Testing:

Parameters

API Testing

Unit Testing

Definition

API testing is used to test the API to ensure that it meets the expectations for functionality, performance, security, etc.

Unit Testing is used to test each unit and to ensure that each unit performs as expected or not.

Carried out

It is carried out by QA team.

It is carried out by developers.

Testing Type

It is mostly Black-box testing.

It is White-box testing.

13. What is the difference between functional and non-functional API testing?

Functional API Testing verifies that an API performs the expected business functions correctly, while Non-Functional API Testing evaluates its performance, security, reliability, and scalability.

Functional API TestingNon-Functional API Testing
Verifies the API's functionality and business logic.Verifies the API's quality attributes such as performance and security.
Checks request and response correctness.Checks response time, throughput, and resource usage.
Validates HTTP methods, status codes, headers, and data.Validates load handling, scalability, and reliability.
Ensures the API returns expected results.Ensures the API performs efficiently under different conditions.
Focuses on what the API does.Focuses on how well the API performs.

14. What is authentication in API testing, its purpose, and common methods?

Authentication verifies the identity of a user or system to access protected API resources, ensuring security and preventing unauthorized access. Its purpose is to safeguard sensitive data and enforce access control. Common methods include:

  • API Keys: Simple key in headers (e.g., X-API-Key: abc123).
  • OAuth: Token-based delegation (e.g., OAuth 2.0 for user authorization).
  • JWT: Token-based authentication for secure and stateless communication.
  • Basic Auth: Base64-encoded username, password in headers.

15. What is a test case for API testing, and what does it include?

An API test case is a set of predefined conditions and steps used to verify that an API functions correctly by validating its requests, responses, business logic, security, and performance.

It includes: Test ID, test description, API endpoint, HTTP method, request data (headers/body/parameters), expected response, and expected status code.

16. What is the difference between a GET and POST request?

GET is used to retrieve data from the server, whereas POST is used to send data to the server to create a new resource.

GETPOST
Retrieves data from the server.Sends data to create a new resource.
Data is sent through the URL as query parameters.Data is sent in the request body.
Data is visible in the URL.Data is not visible in the URL.
Can be cached by browsers.Not cached by default.
Safe and idempotent.Not idempotent.
Used for read operations.Used for create/submit operations.

17. What is the purpose of Headers in API Requests?

Headers are key-value pairs sent with an API request or response that provide additional information about the request, such as authentication, content type, accepted response format, and other communication details.

  • Provide authentication and authorization information (e.g., Bearer Token, API Key).
  • Specify the request and response content type (e.g., Content-Type, Accept).
  • Pass additional metadata required for API communication.
  • Control caching, compression, and connection behavior.

18. What is a Mock API, and When is it Used?

A Mock API is a simulated API that mimics the behavior and responses of a real API, allowing developers and testers to develop and test applications without relying on the actual backend service.

When is it Used?

  • When the actual API is not yet developed or available.
  • To test frontend applications independently of the backend.
  • To simulate different API responses, including success and error scenarios.
  • To perform testing without affecting production or live data.

19. What is Negative Testing in the context of APIs?

Negative Testing is a testing technique that verifies how an API handles invalid, unexpected, or incorrect inputs to ensure it returns appropriate error messages and does not fail unexpectedly.

  • Sending invalid or malformed request data.
  • Omitting mandatory fields or parameters.
  • Using invalid or expired authentication tokens.
  • Sending requests with incorrect HTTP method

20. What is a query parameter in API testing?

A query parameter is a key-value pair appended to the end of an API URL after the ? symbol to pass additional information for filtering, searching, sorting, or paginating data.

Example: GET https://api.example.com/users?country=India&page=2

API Testing Interview Questions for Intermediate

These questions focus on practical automation, scripting, and intermediate concepts for testers.

21. What is API mocking and Why is used ?

API Mocking is the process of creating a simulated version of an API that mimics the behavior and responses of the actual API. It enables developers and testers to develop, test, and validate applications without depending on the availability of the real backend service.

Why API mocking is used:

  • Simulates success, error, and edge-case responses.
  • Reduces dependency on external or third-party services.
  • Prevents testing from affecting production or live data.
  • Speeds up development, testing, and debugging.

22. What is the purpose of HTTP status codes in API testing?

HTTP status codes are standardized three-digit codes returned by the server to indicate the outcome of an API request. They help testers verify whether a request was processed successfully or failed due to client-side or server-side issues.

  • Indicate whether an API request was successful or failed.
  • Help identify client-side and server-side errors.
  • Verify that the API returns the expected response for different scenarios.
  • Assist in debugging and troubleshooting API issues.
http_status_codes
HTTP status codes

23. What is the Purpose of the Request and Response Body in API Testing?

The HTTP Request & Responses body are used to exchange data between the client and the server in API communication.

Purpose of the Request Body

  • Sends input data to the server for processing.
  • Creates or updates resources using methods like POST, PUT, and PATCH.
  • Carries data in formats such as JSON or XML.

Purpose of the Response Body

  • Returns the requested data or operation result.
  • Confirms whether the request was processed successfully.
  • Contains response data, messages, or error details.
Request-and-Response-Cycle
request and response

24. What is API Security Testing, and Why is it Important?

API security testing is the process of verifying that an API is protected against unauthorized access, data breaches, and security vulnerabilities. It ensures that authentication, authorization, data encryption, and other security mechanisms work correctly to safeguard sensitive information.

  • Prevents unauthorized access to API resources.
  • Verifies authentication and authorization mechanisms.
  • Protects sensitive data from leakage and cyberattacks.
  • Identifies security vulnerabilities such as SQL Injection, XSS, and Broken Authentication.

25. What is Boundary Value Analysis (BVA) in API testing?

BVA is a black-box testing technique that verifies an API's behavior by testing input values at their minimum, maximum, and boundary limits, where defects are most likely to occur.

26. What is API versioning, and why is it important in API testing?

API Versioning is the practice of maintaining multiple versions of an API to introduce new features or changes without affecting existing clients or applications that depend on older versions..

Why is API Versioning Important?

  • Ensures backward compatibility with existing applications.
  • Allows new features to be introduced without breaking current integrations.
  • Enables smooth migration from older API versions to newer ones.
  • Helps maintain stability and reliability for different API consumers.

27. What tools could be used for API testing?

API testing tools help testers create, execute, automate, and validate API requests and responses. They support functional, performance, security, and automated testing to ensure APIs work correctly and reliably.

  • Postman: Used to create, test, automate, and manage REST APIs.
  • REST Assured: Java library for automating REST API testing.
  • SoapUI: Tests both SOAP and REST APIs with functional and security testing support.
  • Swagger (OpenAPI): Used to design, document, and test APIs.
  • JMeter: Performs API load, stress, and performance testing.

28. When writing API document, what must be considered?

API documentation should provide clear, accurate, and complete information that helps developers understand how to use, integrate, and test the API effectively.

  • Clearly describe the API's purpose and functionality.
  • Document all API endpoints and supported HTTP methods.
  • Specify request parameters, headers, and request body formats.
  • Include authentication and authorization requirements.

29: How do you test GraphQL APIs compared to REST APIs?

GraphQL API testing focuses on validating queries, mutations, schemas, and the returned fields, whereas REST API testing validates multiple endpoints, HTTP methods, status codes, and resource-based responses.

GraphQL API TestingREST API Testing
Uses a single endpoint for all operations.Uses multiple endpoints for different resources.
Tests queries, mutations, and subscriptions.Tests HTTP methods such as GET, POST, PUT, PATCH, and DELETE.
Validates only the requested fields in the response.Validates the complete resource returned by the endpoint.
Verifies GraphQL schema and query structure.Verifies endpoint functionality, status codes, and responses.
Reduces over-fetching and under-fetching of data.May return more or less data than required.

30. How do you ensure the security of APIs in your tests?

API security is ensured by verifying that the API is protected against unauthorized access, data breaches, and common security vulnerabilities through comprehensive security testing.

How to Ensure API Security

  • Verify authentication mechanisms such as API Keys, OAuth 2.0, JWT, and Basic Authentication.
  • Validate authorization to ensure users can access only permitted resources.
  • Test APIs for common vulnerabilities such as SQL Injection, XSS, and Broken Authentication.
  • Verify secure communication using HTTPS/SSL/TLS encryption.
  • Validate input data to prevent malicious or invalid requests.

31. What are the different types of error responses in API testing?

Error responses in API testing are categorized using HTTP status codes to indicate different types of failures. Here are the different types:

  • Validation errors: Validation errors occur when the API request does not meet the validation criteria defined by the API.
  • HTTP error status codes: These can be client-side status codes or server-side status codes. There are standard HTTP status codes like 4xx or 5xx that indicate errors in the API request or response.
  • Custom error messages: These are the custom error messages that are returned by the API in case of errors or exceptions.

32. How do you handle error responses in your API Tests?

Error responses are handled by validating that the API returns the correct HTTP status code, error message, and response structure for invalid or unexpected requests, ensuring the API behaves reliably and securely.

How to Handle Error Responses

  • Verify the expected HTTP status code (e.g., 400, 401, 403, 404, 500).
  • Validate the error message and error code returned by the API.
  • Check the response body structure and required error fields.
  • Test invalid, missing, or malformed request data.
  • Verify authentication and authorization failure scenarios.

33. What is input validation?

Input validation is the process of verifying that the data sent to an API is correct, complete, and conforms to the expected format, data type, length, and business rules before it is processed.

  • Ensures only valid and correctly formatted data is accepted.
  • Prevents invalid, incomplete, or malicious input.
  • Protects APIs from security vulnerabilities such as SQL Injection and XSS.

34. Why input validation is important in API Testing?

mportance of Input Validation

  • Prevents invalid or malformed data from being processed.
  • Protects APIs against security attacks such as SQL Injection and XSS.
  • Ensures data accuracy and consistency.
  • Verifies compliance with business rules and validation constraints.
  • Reduces application errors and unexpected failures.

35. What is cross-site request forgery (CSRF)?

Cross-site request forgery (CSRF) is a web security attack in which a malicious website tricks an authenticated user into sending unauthorized requests to a trusted application. As a result, the server processes the request using the user's existing session or authentication credentials.

  • Exploits a user's authenticated session.
  • Commonly affects web applications that use cookie-based authentication.
  • Can lead to unauthorized actions such as changing passwords or transferring funds.

API Testing Interview Questions for Experienced

These questions focus on Experienced concepts to help build a strong understanding of API testing with advance concepts.

36. How CSRF can be prevented in API Testing?

CSRF prevention in API testing involves verifying that APIs properly validate requests and reject unauthorized or forged requests. Testers ensure that security mechanisms such as tokens, authentication checks, and request validation are correctly implemented.

Methods to Prevent CSRF

  • Validate the presence and correctness of CSRF tokens for state-changing requests.
  • Verify that requests without valid CSRF tokens are rejected.
  • Use SameSite cookie attributes to restrict cross-site requests.
  • Validate Origin and Referer headers to ensure requests come from trusted sourc

37. What is API Contract Testing?

API Contract Testing is a testing technique that verifies whether the API provider and consumer follow the agreed API contract, including request formats, response structures, data types, and communication rules. It ensures that changes in an API do not break dependent applications or services.

  • Commonly used in microservices and distributed architectures.
  • Validates API behavior without requiring full end-to-end testing.
  • Tools like Pact, Postman, and Spring Cloud Contract support contract testing.

38. Why is API Contract Testing Important?

API Contract Testing is important because it ensures that API providers and consumers maintain compatibility by validating that both sides follow the agreed API contract. It helps identify breaking changes early and prevents integration failures in distributed systems.

Importance of API Contract Testing

  • Ensures compatibility between API consumers and providers.
  • Detects breaking changes before they impact dependent applications.
  • Prevents integration failures in microservices and distributed architectures.
  • Validates request and response formats, schemas, and data types.
  • Reduces dependency on complex end-to-end testing.
  • Enables independent development and deployment of services.

39. What is API Performance Testing?

API Performance Testing is a type of non-functional testing that evaluates an API's speed, responsiveness, stability, and scalability under different levels of workload. It ensures that the API can handle expected and unexpected traffic while maintaining acceptable performance.

Key Areas Tested in API Performance Testing

  • Measures API response time and latency.
  • Evaluates throughput (number of requests processed per second).
  • Tests API behavior under normal, peak, and heavy workloads.

40. Why is API Performance Testing Important?

API performance testing ensures that an API is fast, scalable, and reliable under different workloads.

  • Ensures APIs respond quickly under different workload conditions.
  • Verifies API stability during normal, peak, and unexpected traffic.
  • Identifies performance bottlenecks in applications, databases, and infrastructure.
  • Ensures APIs can scale as the number of users and requests increases.
  • Helps maintain service reliability and availability.

41. What is API monitoring?

API monitoring is the process of continuously tracking an API’s availability, performance, and functionality to detect issues in real-time.

  • Uptime & Downtime: Ensures the API is always accessible.
  • Response Time: Tracks API speed and latency.
  • Error Rates: Detects failed requests or unexpected responses.
  • Traffic & Load: Monitors API usage patterns.
  • Security Threats: Identifies potential vulnerabilities.

42. Why is API monitoring important?

API Monitoring is important because it ensures APIs remain available, reliable, and performant in production by continuously tracking their health, response time, and failures. It helps teams quickly detect and resolve issues before they impact users and business operations.

  • Ensures API availability and uptime for users and applications.
  • Detects failures, errors, and performance degradation in real time.
  • Helps identify slow response times and latency issues.
  • Provides early alerts to prevent major service disruptions.
  • Ensures APIs meet performance standards and SLAs.

43. What is API virtualization?

API Virtualization is a technique that creates a simulated version of an API or service to replicate the behavior, responses, and performance of a real API. It allows developers and testers to develop and test applications without depending on the availability of actual backend systems or third-party services.

44. Why API virtualization is used in API testing?

IAPI Virtualization is used in API testing to simulate unavailable, expensive, or complex services, allowing testers to validate application behavior without depending on real backend systems. It helps improve testing speed, coverage, and reliability.

  • Enables testing when dependent APIs or services are unavailable.
  • Allows teams to test APIs before backend development is completed.
  • Reduces dependency on third-party systems and external services.

45. What is the Purpose of API Documentation in API Testing?

API Documentation provides detailed information about API functionality, endpoints, request/response formats, authentication, and usage guidelines. It helps testers understand, design, execute, and validate API test cases effectively.

  • Provides details about API endpoints and supported HTTP methods.
  • Defines request parameters, headers, and body formats.
  • Describes expected responses, status codes, and error messages.
  • Helps testers create accurate and complete test cases.
  • Defines authentication and authorization requirements.

46. How do you prioritize API test cases for regression testing?

API test case prioritization for regression testing involves selecting and ordering test cases based on business impact, risk, recent code changes, and critical API functionality. The goal is to identify defects quickly while ensuring maximum test coverage with available time and resources.

Factors Used to Prioritize API Test Cases

  • Prioritize APIs that support critical business functions and high user impact.
  • Execute test cases related to recent code changes or bug fixes first.
  • Give higher priority to frequently used and high-traffic APIs.
  • Prioritize tests for authentication, authorization, and security-critical APIs.

Regression Testing Priority Levels

  • High Priority: Critical APIs, payment flows, authentication, and core business operations.
  • Medium Priority: Important features with moderate business impact.
  • Low Priority: Less frequently used features or minor changes.

47. How to handle versioning in API testing?

API versioning in testing involves validating multiple API versions to ensure new changes, enhancements, or fixes do not break existing functionality. Testers verify backward compatibility, version-specific behavior, and smooth migration between API versions.

How to Handle API Versioning in Testing

  • Maintain separate test suites for each supported API version.
  • Validate backward compatibility between old and new versions.
  • Test version-specific endpoints, request formats, and response structures.
  • Verify that deprecated API versions behave as expected until retirement.

48. List the challenges faced while performing API testing.

API Testing involves validating backend services and integrations, but testers may face challenges related to documentation, security, data management, dependencies, and changing API requirements.

  • Lack of proper or updated API documentation.
  • Complex authentication and authorization mechanisms.
  • Difficulty in managing and maintaining test data.
  • Frequent changes in API requirements and contracts.

49. What are the different bugs that can be found in API testing?

API testing helps identify defects related to functionality, data handling, security, performance, and communication between different systems. These bugs can affect API reliability, security, and user experience.

  • Incorrect HTTP status codes returned for requests.
  • Invalid or incorrect response data.
  • Missing or incorrect response fields.
  • Incorrect data validation and input handling.

50. Is it possible to hack API while testing?

Yes, APIs can be tested for security vulnerabilities using ethical hacking techniques, but it must be performed only in an authorized testing environment. API security testing helps identify weaknesses before attackers can exploit them.

Common API Vulnerabilities Exploited:

  • Testers can perform authorized security checks to identify API vulnerabilities.
  • Security testing focuses on finding weaknesses such as:
  • Broken authentication and authorization issues.
  • Injection attacks (SQL Injection, Command Injection).
  • Data exposure vulnerabilities.

51. How do you perform API Load Testing?

API load testing is a type of performance testing that is done to check the application's capability to perform under various user loads. It is done by simulating many users hitting the API at the same time to identify if the application is capable of handling the load by maintaining the consistency in the response times and not impacting the functionality.

load_testing
API Load Testing

52. What is the Test Environment of API?

An API test environment is a setup that provides all required hardware, software, services, configurations, and data needed to validate API functionality, performance, security, and integration before deploying it to production.

  • Server & Database: A dedicated test server and database to mimic production.
  • API Endpoints: Staging or sandbox URLs separate from live systems.
  • Authentication & Security Setup: API keys, OAuth, JWT tokens for access control.
  • Mock Services & Virtualization: Simulated dependencies for testing APIs in isolation.
  • Testing Tools: Tools like Postman, JMeter, SoapUI for automation and performance testing.
  • Logging & Monitoring: Tracks API requests, responses, and failures.

Practical API Testing Interview Questions

Below are intermediate-level, hands-on API testing questions with detailed solutions, code snippets, and outputs, tailored for SDETs and testers preparing for interviews.

1. Write a RestAssured script to validate a POST API for creating a user, including response schema and status code.

Steps:

  • Set up RestAssured with the base URI.
  • Send a POST request with a JSON payload containing user details.
  • Validate the status code and response fields.
  • Validate response structure using JSON schema.
  • Extract and print the created user ID.
Java
import io.restassured.RestAssured;
import io.restassured.module.jsv.JsonSchemaValidator;
import io.restassured.response.Response;
import org.testng.Assert;
import org.testng.annotations.Test;

import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class PostApiTest {

    @Test
    public void testCreateUserAPI() {

        // Set base URI
        RestAssured.baseURI = "https://reqres.in/api";

        // Request payload
        String requestBody = "{\n" +
                "  \"name\": \"Alice\",\n" +
                "  \"job\": \"Engineer\"\n" +
                "}";

        // Send POST request and validate response
        Response response =
                given()
                    .header("Content-Type", "application/json")
                    .body(requestBody)
                .when()
                    .post("/users")
                .then()
                    .statusCode(201)
                    .body("name", equalTo("Alice"))
                    .body("job", equalTo("Engineer"))
                    .body(JsonSchemaValidator.matchesJsonSchemaInClasspath("user-schema.json"))
                    .extract()
                    .response();

        // Extract user ID
        String userId = response.jsonPath().getString("id");

        System.out.println("Created User ID: " + userId);

        // Validate user ID is generated
        Assert.assertNotNull(userId, "User ID should not be null");
    }
}

JSON Schema File (user-schema.json)

Location: src/test/resources/user-schema.json

{

"type": "object",
"properties": {
"name": {
"type": "string"
},
"job": {
"type": "string"
},
"id": {
"type": "string"
},
"createdAt": {
"type": "string"
}
},
"required": [
"name",
"job",
"id",
"createdAt"
]
}

Output: Created User ID: 123

Validations Performed

  • Validates API returns 201 Created status code.
  • Verifies response contains correct name and job values.
  • Validates response structure using JSON schema.
  • Extracts and validates the generated user ID.
  • Ensures API response matches the expected contract.

2. Write a Postman Script to Chain a GET and POST Request, Passing Data Dynamically

Steps:

  • Send a GET request to retrieve user data.
  • Extract and store the user ID in an environment variable.
  • Use the stored user ID dynamically in a POST request.
  • Validate the POST response.

Step 1: GET Request

Request: GET https://reqres.in/api/users/2

JavaScript
// Parse GET response
let responseData = pm.response.json();

// Extract user ID
let userId = responseData.data.id;

// Store user ID in environment variable
pm.environment.set("userId", userId);

console.log("Stored User ID: " + userId);

Step 2: POST Request

Request: POST https://reqres.in/api/users

Headers: Content-Type: application/json

Body (raw JSON):

{
"name": "John",
"job": "QA Engineer",
"userId": "{{userId}}"
}

POST Request Test Script

JavaScript
// Validate status code
pm.test("Status code should be 201", function () {
    pm.response.to.have.status(201);
});

// Parse response
let responseData = pm.response.json();

// Validate user ID
pm.test("User ID should match", function () {
    pm.expect(responseData.userId)
        .to.eql(pm.environment.get("userId"));
});

// Print created user ID
console.log("Post created with userId: " + responseData.userId);

Output:

Stored User ID: 2
Post created with userId: 2

Validations Performed

  • GET request successfully retrieves user data.
  • User ID is extracted and stored dynamically.
  • POST request uses the stored ID from the environment variable.
  • Response status code is validated as 201 Created.
  • Response user ID is matched with the stored value.

3. Write a RestAssured script to test a DELETE API and verify resource removal.

Steps:

  • Set up RestAssured with the base URI.
  • Send a DELETE request to remove the resource.
  • Validate the response status code.
  • Send a GET request for the same resource.
  • Verify that the resource no longer exists.

RestAssured Test Script

Java
import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.testng.annotations.Test;

import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class DeleteApiTest {

    @Test
    public void testDeleteUser() {

        // Set Base URI
        RestAssured.baseURI = "https://reqres.in/api";

        int userId = 2;

        // Delete the user
        given()
        .when()
            .delete("/users/" + userId)
        .then()
            .statusCode(204);

        System.out.println("User deleted successfully.");

        // Verify resource is removed
        Response response =
                given()
                .when()
                    .get("/users/" + userId)
                .then()
                    .extract()
                    .response();

        // Validate resource no longer exists
        response.then()
                .statusCode(404);

        System.out.println("Resource removal verified.");
    }
}

Output:

User deleted successfully.
Resource removal verified.

Validations Performed

  • Sets the RestAssured base URI.
  • Sends a DELETE request to remove the resource.
  • Verifies the API returns 204 No Content.
  • Sends a GET request for the deleted resource.
  • Verifies the resource is no longer available by checking 404 Not Found.

4. Write a Postman Script to Validate API Response Time and Handle Rate Limiting

Steps:

  • Send an API request.
  • Validate the response time.
  • Check the HTTP status code.
  • Handle rate limiting (HTTP 429).
  • Validate the Retry-After header if rate limiting occurs.

Request: GET https://reqres.in/api/users/2

JavaScript
// Validate response time
pm.test("Response time is less than 1000 ms", function () {
    pm.expect(pm.response.responseTime).to.be.below(1000);
});

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

// Handle rate limiting
if (pm.response.code === 429) {

    pm.test("Rate limit exceeded", function () {
        pm.expect(pm.response.code).to.eql(429);
    });

    // Validate Retry-After header
    pm.test("Retry-After header exists", function () {
        pm.expect(pm.response.headers.has("Retry-After")).to.be.true;
    });

    console.log("Rate limit exceeded. Retry after: "
        + pm.response.headers.get("Retry-After") + " seconds");

} else {

    console.log("Response Time: "
        + pm.response.responseTime + " ms");
}

Expected Output: Response Time: 245 ms

OR (if rate limit is exceeded): Rate limit exceeded. Retry after: 60 seconds

Validations Performed

  • Validates response time is within the acceptable limit.
  • Verifies the API returns 200 OK for successful requests.
  • Detects 429 Too Many Requests responses.
  • Validates the Retry-After header when rate limiting occurs.
  • Logs response time or retry information for analysis.

5. Write a RestAssured Script to Test a GraphQL API Query

Steps:

  • Set up RestAssured with the GraphQL endpoint.
  • Create a GraphQL query in JSON format.
  • Send a POST request to the GraphQL endpoint.
  • Validate the response status code and returned data.
  • Extract and print the required response fields.

RestAssured Test Script

Java
import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.testng.Assert;
import org.testng.annotations.Test;

import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class GraphQLApiTest {

    @Test
    public void testGraphQLQuery() {

        // Set Base URI
        RestAssured.baseURI = "https://countries.trevorblades.com";

        // GraphQL Query
        String requestBody = "{"
                + "\"query\":\"query { country(code: \\\"IN\\\") { name capital currency } }\""
                + "}";

        // Send POST request
        Response response =
                given()
                    .header("Content-Type", "application/json")
                    .body(requestBody)
                .when()
                    .post("/")
                .then()
                    .statusCode(200)
                    .body("data.country.name", equalTo("India"))
                    .extract()
                    .response();

        // Extract response values
        String country = response.jsonPath().getString("data.country.name");
        String capital = response.jsonPath().getString("data.country.capital");
        String currency = response.jsonPath().getString("data.country.currency");

        // Print values
        System.out.println("Country : " + country);
        System.out.println("Capital : " + capital);
        System.out.println("Currency: " + currency);

        // Assertions
        Assert.assertEquals(country, "India");
        Assert.assertNotNull(capital);
        Assert.assertNotNull(currency);
    }
}

Expected Output

Country : India
Capital : New Delhi
Currency: INR

Validations Performed

  • Sets the GraphQL API endpoint.
  • Sends a GraphQL query using a POST request.
  • Validates the response status code (200 OK).
  • Verifies the returned country name is India.
  • Extracts and validates the capital and currency.

6. Write a JMeter script to perform load testing on a GET API.

Steps:

  • Create a Thread Group with 50 users, 30-second duration.
  • Add an HTTP Request sampler for the GET endpoint.
  • Add listeners (Summary Report, View Results Tree).
  • Run the test and analyze results.

JMeter Setup:

Thread Group:

  • Number of Threads: 50
  • Ramp-up Period: 10 seconds
  • Loop Count: Forever
  • Duration: 30 seconds

HTTP Request:

  • Method: GET
  • Path: /api/users?page=2
  • Server Name: reqres.in

Listeners: Summary Report, View Results Tree

Sample JMeter Script (exported XML snippet):

XML
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Thread Group">
  <elementProp name="ThreadGroup.on_sample_error" elementType="Argument">
    <stringProp name="Argument.value">continue</stringProp>
  </elementProp>
  <stringProp name="ThreadGroup.num_threads">50</stringProp>
  <stringProp name="ThreadGroup.ramp_time">10</stringProp>
  <stringProp name="ThreadGroup.scheduler">true</stringProp>
  <stringProp name="ThreadGroup.duration">30</stringProp>
</ThreadGroup>
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Request">
  <stringProp name="HTTPSampler.domain">reqres.in</stringProp>
  <stringProp name="HTTPSampler.path">/api/users?page=2</stringProp>
  <stringProp name="HTTPSampler.method">GET</stringProp>
</HTTPSamplerProxy>

Output:

Label: HTTP Request
Samples: 1200
Average: 150ms
Throughput: 40/sec
Error %: 0%

Test passes if no errors and average response time is acceptable (<200ms).

7. Write a RestAssured script to test an API with OAuth 2.0 authentication.

Steps:

  • Set up RestAssured with the base URI.
  • Provide the OAuth 2.0 access token.
  • Send an authenticated API request.
  • Validate the response status code and response data.
  • Extract and print the response.

RestAssured Test Script

Java
import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.testng.Assert;
import org.testng.annotations.Test;

import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class OAuth2ApiTest {

    @Test
    public void testOAuth2Authentication() {

        // Set Base URI
        RestAssured.baseURI = "https://api.example.com";

        // OAuth 2.0 Access Token
        String accessToken = "your_access_token";

        // Send authenticated GET request
        Response response =
                given()
                    .auth()
                    .oauth2(accessToken)
                    .header("Content-Type", "application/json")
                .when()
                    .get("/users/profile")
                .then()
                    .statusCode(200)
                    .body("status", equalTo("success"))
                    .extract()
                    .response();

        // Print response
        System.out.println(response.asPrettyString());

        // Validate response
        Assert.assertEquals(response.getStatusCode(), 200);
    }
}

Expected Output

Status Code: 200

{
"status": "success",
"id": 101,
"name": "John Doe",
"email": "john@example.com"
}

Validations Performed

  • Sets the RestAssured base URI.
  • Authenticates the request using an OAuth 2.0 Bearer Token.
  • Sends an authenticated GET request.
  • Verifies the API returns HTTP 200 OK.
  • Validates the response field (status = "success").
  • Extracts and prints the API response.

8. Write a Postman Script to Perform Negative Testing on a POST API

Steps:

  • Send a POST request with invalid or missing data.
  • Validate the API returns the expected error status code.
  • Verify the error message in the response.
  • Ensure the API handles invalid requests gracefully.

Request: POST https://reqres.in/api/users

Headers: Content-Type: application/json

Body (Invalid Request)

{
"name": "",
"job": null
}

Postman Test Script

JavaScript
// Validate status code
pm.test("Status code should be 400 or 422", function () {
    pm.expect([400, 422]).to.include(pm.response.code);
});

// Parse response
let responseData = pm.response.json();

// Validate error message exists
pm.test("Error message is present", function () {
    pm.expect(responseData.error).to.not.be.undefined;
});

// Validate response time
pm.test("Response time is less than 1000 ms", function () {
    pm.expect(pm.response.responseTime).to.be.below(1000);
});

// Print error message
console.log("Error:", responseData.error);

Expected Output

Status Code: 400

{
"error": "Invalid input data"
}

Validations Performed

  • Sends a POST request with invalid input data.
  • Verifies the API returns an appropriate error status code (400 Bad Request or 422 Unprocessable Entity).
  • Validates the error message in the response.
  • Ensures the API handles invalid requests without crashing.
  • Confirms the response time is within the acceptable limit.
Comment

Explore