API Testing Interview Questions And Answers

Last Updated : 1 Sep, 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 Fresher s

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 enables different software applications to communicate and exchange data. It defines how one application can request services or information from another without needing to know its internal implementation.

frame_3258
API

Types of APIs

APIs are commonly classified based on their access and usage:

  • Public APIs (Open APIs): Available for external developers and the general public to use.
  • Private APIs (Internal APIs): Used within an organization to connect internal applications and services.
  • Partner APIs: Shared with specific business partners or authorized users.
  • Composite APIs: Combine multiple API requests or services into a single request.

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.

An API enables communication between software components, while a web service is an API that provides communication between applications over a network.

ParameterAPIWeb Service
DefinitionAn interface that enables communication between software applications or components.A network-based interface that enables communication between applications.
Network RequirementCan work locally or over a network.Requires a network connection.
CommunicationCan use different communication methods and protocols.Typically uses web protocols such as HTTP/HTTPS.
Data FormatCan exchange data in various formats, including JSON, XML, and binary.Commonly exchanges data using JSON or XML.
ScopeA broader concept that includes different types of software interfaces.A specific type of API designed for network-based communication.

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.

API Testing verifies the functionality and communication of an API, while Unit Testing verifies individual units of code in isolation.

ParameterAPI TestingUnit Testing
DefinitionTests APIs to verify their functionality, request-response behavior, and integration with other components.Tests individual units, such as functions, methods, or classes, to verify that they work correctly.
ScopeFocuses on API behavior and communication between application components.Focuses on the smallest testable unit of an application.
Performed ByCan be performed by QA engineers, developers, or automation engineers.Primarily performed by developers.
Testing TypeCommonly performed as black-box testing through API requests and responses.Primarily performed as white-box testing based on internal code logic.
DependenciesMay interact with actual services, databases, or other application components.External dependencies are usually isolated using mocks or stubs.
Common ToolsPostman, REST Assured, SoapUI, and Karate.JUnit, TestNG, NUnit, and pytest.

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 documented set of conditions used to verify whether an API produces the expected result for a specific request.

An API test case typically includes:

  • Test Case ID: A unique identifier for the test case.
  • Test Scenario: The functionality or behavior being tested.
  • API Request: The endpoint, HTTP method, headers, parameters, authentication, and request body.
  • Expected Result: The expected status code and response behavior.
  • Actual Result: The response obtained during execution.
  • Test Status: Indicates whether the test case passed or failed.

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.

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 evaluating an API for security vulnerabilities and verifying that it properly protects data, authentication credentials, and system resources from unauthorized access or attacks.

It is important because APIs often expose sensitive data and business functionality. Security testing helps:

  • Identify vulnerabilities such as broken authentication, broken authorization, and improper input validation.
  • Prevent unauthorized access and data breaches.
  • Protect sensitive information and ensure secure communication between systems.
  • Reduce security risks before the API is deployed to production.

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

BVA is a black-box testing technique that checks how an API handles input values at the edges of an allowed range, where defects are more likely to occur.

  • Tests values at and around the minimum and maximum limits.
  • Helps identify input validation defects at boundary conditions.
  • Verifies that the API accepts valid limits and rejects invalid values outside the range.

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

API versioning is the practice of managing changes to an API by maintaining different versions, allowing existing clients to continue working while newer versions introduce updates or improvements.

  • Ensures backward compatibility when API changes are introduced.
  • Allows testers to validate functionality across different API versions.
  • Helps identify version-specific issues and compatibility problems.

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 requested data fields, whereas REST API testing focuses on validating endpoints, HTTP methods, status codes, and responses.

GraphQL API TestingREST API Testing
Commonly uses a single endpoint for different operations.Typically uses multiple endpoints for different resources.
Tests queries, mutations, and subscriptions.Tests HTTP methods such as GET, POST, PUT, PATCH, and DELETE.
Validates the requested fields and response structure.Validates the response data returned by each endpoint.
Verifies the GraphQL schema and GraphQL-specific errors.Verifies HTTP status codes and endpoint-specific error responses.
Focuses on validating client-defined data requests.Focuses on validating resource-based operations.

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.

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.
  • Ensures APIs meet performance standards and SLAs.

43. What is API virtualization?

API virtualization is a testing technique that simulates the behavior of an API when the actual API or its dependent services are unavailable, incomplete, unstable, or difficult to access. It uses a virtual service to return predefined responses that mimic the behavior of the real API.

  • Enables testing without relying on unavailable or unstable dependencies.
  • Allows teams to simulate different responses, errors, and edge cases.
  • Supports early and independent testing during development.

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.

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

API test cases for regression testing are prioritized based on business impact, risk, usage frequency, and the areas affected by recent changes. Critical API functionality is tested first to identify major regressions early.

  • High Priority: Critical business workflows, high-risk APIs, frequently used APIs, and recently modified functionality.
  • Medium Priority: Important functionality with moderate business impact or risk.
  • Low Priority: Stable and rarely used functionality with low business impact and risk.

47. How to handle versioning in API testing?

API versioning in testing involves validating different versions of an API to ensure that new changes do not break existing clients. Testers should verify both the functionality of the new version and compatibility with supported older versions.

  • Test each API version independently based on its documented requirements.
  • Verify backward compatibility between supported API versions.
  • Update test cases when endpoints, request formats, response structures, or behavior change.

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.

  • 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 the reliability and security of an API.

  • Incorrect HTTP status codes, response data, or missing response fields.
  • Improper input validation, authentication, authorization, or error handling.
  • Slow response times, performance issues, or failures in communication with dependent services.

50. Is it possible to hack API while testing?

Yes, security testing can identify vulnerabilities that could allow an API to be compromised. However, security testing should only be performed on APIs that you own or have explicit authorization to test.

  • Test for vulnerabilities such as broken authentication, improper authorization, and insecure input handling.
  • Verify that sensitive data and API endpoints are properly protected.
  • Perform authorized security testing in a controlled environment to identify and fix vulnerabilities before attackers can exploit them.

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.

RestAssured can test a POST API by sending user data, validating the response status code, and verifying that the response matches a predefined JSON schema.

Steps

  • Set the base URI of the API.
  • Create the request body with user details.
  • Send a POST request to create the user.
  • Validate the HTTP status code.
  • Validate the response against a JSON schema.
  • Verify important response fields.

RestAssured Test Script

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

import java.io.File;

import static io.restassured.RestAssured.*;
import static io.restassured.module.jsv.JsonSchemaValidator.*;
import static org.hamcrest.Matchers.*;

public class CreateUserApiTest {

    @Test
    public void testCreateUser() {

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

        // Request body
        String requestBody = """
        {
            "name": "John Doe",
            "job": "QA Engineer"
        }
        """;

        // Send POST request and validate response
        Response response =
                given()
                    .contentType("application/json")
                    .body(requestBody)
                .when()
                    .post("/users")
                .then()
                    .statusCode(201)
                    .body(matchesJsonSchemaInClasspath("create-user-schema.json"))
                    .body("name", equalTo("John Doe"))
                    .body("job", equalTo("QA Engineer"))
                    .extract()
                    .response();

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

Response JSON Schema

Create a file named create-user-schema.json inside: src/test/resources/

{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"name": {
"type": "string"
},
"job": {
"type": "string"
},
"id": {
"type": "string"
},
"createdAt": {
"type": "string"
}
},
"required": [
"name",
"job",
"id",
"createdAt"
]
}

Validations Performed

  • Sends a POST request to create a new user.
  • Verifies that the API returns 201 Created.
  • Validates the response structure using a JSON schema.
  • Checks that the returned name and job values match the request data.
  • Extracts and prints the API response.

Note: To use matchesJsonSchemaInClasspath(), the RestAssured JSON Schema Validator dependency must be included in the project.

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

Request chaining allows data from one API response to be extracted and used dynamically in another API request.

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

Tests Script

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

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

// Store user ID in an 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
const responseData = pm.response.json();

// Validate user ID
pm.test("User ID should match", function () {
    pm.expect(String(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

  • Retrieves user data using a GET request.
  • Extracts the user ID dynamically from the response.
  • Stores the user ID in an environment variable.
  • Passes the stored user ID to the POST request.
  • Verifies that the POST request returns 201 Created.
  • Confirms that the returned user ID matches the stored value.

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

A DELETE API request removes a resource from the server. The resource removal can be verified by sending a GET request for the same resource and confirming that it returns 404 Not Found.

Steps

  • Set up RestAssured with the base URI.
  • Send a DELETE request to remove the resource.
  • Validate the DELETE 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 org.testng.annotations.Test;

import static io.restassured.RestAssured.*;

public class DeleteApiTest {

    @Test
    public void testDeleteAndVerifyResourceRemoval() {

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

        // Resource ID
        int userId = 101;

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

        // Verify that the resource no longer exists
        given()
        .when()
            .get("/users/" + userId)
        .then()
            .statusCode(404);

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

Output:

User deleted successfully.
Resource removal verified.

Validations Performed

  • Sets the RestAssured base URI.
  • Sends a DELETE request to remove the resource.
  • Verifies a successful DELETE response.
  • Sends a GET request for the same resource.
  • Verifies that the resource returns 404 Not Found.

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

Postman can validate whether an API responds within an acceptable time limit and detect rate limiting. Rate limiting is commonly indicated by the HTTP status code 429 Too Many Requests.

Steps

  • Send a request to the API endpoint.
  • Validate that the response time is within the acceptable limit.
  • Check whether the API returns status code 429.
  • If rate limiting occurs, check the Retry-After header when available.
  • Validate that the API response is handled correctly.

Postman Test Script

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

// Check for rate limiting
pm.test("Handle rate limiting", function () {

    if (pm.response.code === 429) {

        console.log("Rate limit exceeded.");

        const retryAfter = pm.response.headers.get("Retry-After");

        if (retryAfter) {
            console.log("Retry after:", retryAfter, "seconds");
        }

        pm.expect(pm.response.code).to.eql(429);

    } else {
        pm.expect(pm.response.code).to.not.eql(429);
        console.log("Request completed successfully.");
    }
});

Validations Performed

  • Verifies that the API response time is less than 1000 ms.
  • Detects the 429 Too Many Requests status code.
  • Reads the Retry-After header when rate limiting occurs.
  • Logs appropriate information for successful and rate-limited requests.

Note: The acceptable response-time limit and rate-limiting behavior should be based on the API's performance requirements and documentation.

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

GraphQL APIs typically use a POST request where the query is sent in the request body. RestAssured can send the GraphQL query and validate the API response.

Steps:

  • Set the GraphQL API endpoint.
  • Create the GraphQL query.
  • Send the query using a POST 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.annotations.Test;

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

public class GraphQLApiTest {

    @Test
    public void testGraphQLQuery() {

        // Set GraphQL API endpoint
        RestAssured.baseURI = "https://api.example.com";

        // GraphQL query
        String query = "{ user(id: 1) { id name email } }";

        // Send POST request
        Response response =
                given()
                    .contentType("application/json")
                    .body("{\"query\":\"" + query + "\"}")
                .when()
                    .post("/graphql")
                .then()
                    .statusCode(200)
                    .body("data.user.id", equalTo("1"))
                    .extract()
                    .response();

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

Example GraphQL Request Body

{
"query": "{ user(id: 1) { id name email } }"
}

Validations Performed

  • Sends a GraphQL query using a POST request.
  • Verifies that the API returns HTTP status code 200.
  • Validates the returned user data.
  • Extracts and prints the API response.

Note: The endpoint, query, and expected response values should be updated according to the actual GraphQL API schema.

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

Apache JMeter can perform load testing on a GET API by simulating multiple users sending requests simultaneously. This test helps measure response time, throughput, latency, and error rate.

Steps

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

JMeter Setup

Thread Group

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

HTTP Request

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

Listeners

  • Summary Report
  • View Results Tree

Sample JMeter Configuration

XML
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Thread Group">
    <stringProp name="ThreadGroup.num_threads">50</stringProp>
    <stringProp name="ThreadGroup.ramp_time">10</stringProp>
    <boolProp name="ThreadGroup.scheduler">true</boolProp>
    <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.protocol">https</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%

The test results should be evaluated based on the application's defined performance requirements, such as acceptable response time, throughput, and error rate.

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

RestAssured supports OAuth 2.0 authentication by sending an access token as a Bearer token with the API request. The response can then be validated using status code and response body assertions.

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.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 and validate response
        Response response =
                given()
                    .auth()
                    .oauth2(accessToken)
                    .header("Accept", "application/json")
                .when()
                    .get("/users/profile")
                .then()
                    .statusCode(200)
                    .body("status", equalTo("success"))
                    .extract()
                    .response();

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

Expected Output

{
"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 access token.
  • Sends an authenticated GET request.
  • Verifies that the API returns HTTP status code 200.
  • Validates that the status field is success.
  • Extracts and prints the API response.

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

Negative testing verifies how an API handles invalid, missing, or incorrect input data. The test ensures that the API returns an appropriate error response instead of successfully processing invalid data.

Steps

  • Create a POST request with invalid or missing input data.
  • Send the request to the API endpoint.
  • Verify that the API returns the expected error status code.
  • Validate the error message in the response.
  • Check that the API handles the invalid request properly.

Request: POST https://api.example.com/users

Headers: Content-Type: application/json

Body (Invalid Request)

{
"name": "",
"email": "invalid-email"
}

Postman Test Script

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

pm.test("Response should contain an error message", function () {
    const responseData = pm.response.json();

    pm.expect(
        responseData.error || responseData.message
    ).to.exist;
});

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

console.log("Response:", pm.response.json());

Expected Output

{
"error": "Invalid input data"
}

Validations Performed

  • Validations Performed
  • Sends invalid data to a POST API.
  • Verifies that the API returns an appropriate validation error.
  • Checks for an error or message in the response.
  • Ensures the API handles invalid requests gracefully.
  • Validates the API response time.

Note: The exact status code and error response depend on the API specification. Common validation error codes are 400 Bad Request and 422 Unprocessable Content.

Comment

Explore