API Testing Interview Questions And Answers

Last Updated : 19 May, 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 verifies the functionality, performance, and security of application programming interfaces (APIs) by sending requests and validating responses. It is important because APIs enable communication between systems, and testing ensures the reliability and correctness of the software product.

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: APIs that work over the internet using HTTP/HTTPS protocols. They allow communication between client and server applications and commonly use REST or SOAP architecture.
  • Local APIs: APIs used for communication between applications or components within the same system or device.
  • Remote APIs: APIs that enable communication between systems running on different servers or networks, often using Remote Procedure Calls (RPC) or web services.
  • Library/Framework APIs: APIs provided by programming libraries or frameworks that allow developers to use predefined functions and services in their applications.

3. What is an endpoint in API testing?

An endpoint is a specific URL or route in an API that performs a function, accepting requests and returning responses.

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 and SOAP are two different approaches used for building APIs and enabling communication between systems.

  • REST (Representational State Transfer): An architectural style that uses standard HTTP methods such as GET, POST, PUT, PATCH, and DELETE. REST APIs are lightweight, stateless, and commonly use JSON for data exchange, although XML and other formats are also supported.
  • SOAP (Simple Object Access Protocol): A protocol-based messaging framework that uses XML for communication. SOAP APIs are more strict, secure, and standardized, commonly used in enterprise-level applications.
SOAP APIREST API
Protocol-basedArchitectural style
Uses only XML formatCommonly uses JSON, but also supports XML
Works with WSDL (Web Services Description Language)Uses URI and HTTP methods
More secure and standardizedLightweight and faster
More complex and heavyweightSimple and easy to implement
Commonly used in enterprise applicationsCommonly used in web and mobile applications

6. Mention Common HTTP Methods used in API Testing.

Here are the Common HTTP Methods of API Testing.

  • POST: It is used to create new data or resources on an API.
  • GET: It is used to retrieve data or resources from an API.
  • PUT: It is used to update existing data or resources on an API.
  • PATCH: It is used to update existing data or resources from an API partially.
  • DELETE: It is used to delete data or resources from an API.

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 tool for designing, testing, and automating API requests. It allows sending requests, validating responses, and scripting tests.

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 can be used to test various protocols that facilitate communication between software systems. Some commonly tested protocols include:

  • HTTP/HTTPS: Used for REST APIs and web communication.
  • SOAP: XML-based messaging protocol for web services.
  • WebSockets: Enables real-time bidirectional communication.
  • GraphQL: A query language and runtime for APIs.
  • gRPC: High-performance RPC framework using HTTP/2.

Note: REST is an architectural style commonly implemented over HTTP.

11. Tell me Advantages and Limitations of API Testing.

Advantages

  • Faster bug fixes: API testing helps identify issues early in development, thus it helps to diagnose problems earlier in the development of the system allowing for efficient bug detection and removal.
  • Reduced costs: Early bug detection and automation reduce maintenance and testing costs, thus reducing the cost of testing.
  • Multi-language support: API testing provides support for many different languages like JavaScript, Ruby, Python, and PHP. Formats like XML, and JSON are supported during API testing.

Limitations of API Testing

  • Requires Technical Skills: API testing requires skilled and experienced testers who understand APIs, request methods, and response handling.
  • Time-Consuming Process: Creating, maintaining, and executing API test scripts can take a significant amount of time.
  • Limited Documentation Issues: Incomplete or unclear API documentation makes it difficult for testers to understand the expected behavior of the API.

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: Tests API logic and behavior (e.g., correct response data).
  • Non-functional: Tests performance, security, and scalability (e.g., response time).

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?

A test case outlines steps to validate an API, including: Test ID, description, endpoint, method, request data, expected response, and status code.

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

GET and POST are HTTP request methods used to communicate between a client and a server.

  • GET: Retrieves data from the server, is idempotent, and sends parameters in the URL.
  • POST: Sends data to the server to create a new resource, is non-idempotent, and sends data in the request body.

17. What is the purpose of headers in API requests?

Headers provide metadata about the request/response, such as content type, authorization, or caching instructions.

18. What is a mock API, and when is it used?

A mock API simulates real API behavior for testing when the actual API is unavailable, using tools like WireMock or Mockoon.

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

Negative testing verifies how an API behaves when invalid, unexpected, or unauthorized inputs are provided, such as incorrect data formats, missing parameters, or unauthorized requests. It ensures proper error handling and system reliability.

20. What is a query parameter in API testing?

Query parameters are key-value pairs in the URL to filter or modify a request, appended after a ?.

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 simulating the behavior of a real API during testing without calling the actual API. A mock API returns predefined responses, allowing developers and testers to test applications independently of real backend services. It is especially useful during the development and testing stages when the actual API is unavailable, incomplete, or unstable.

Why API mocking is used:

  • Helps test applications that depend on external APIs or third-party services.
  • Allows developers and testers to work independently before the real API is ready.
  • Enables early testing during the initial development stages.
  • Helps simulate different API responses, including errors and edge cases.
  • Improves testing speed and reliability by avoiding dependency on live systems.
  • Supports unit testing, integration testing, and consumer testing effectively.

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

HTTP status codes indicate the result of an API request, helping testers understand whether the request was successful, failed, or requires action.

  • Indicate Response Status: Shows if the request succeeded (200 OK), failed (400 Bad Request), or needs authentication (401 Unauthorized).
  • Aid Debugging: Helps identify issues like server errors (500 Internal Server Error).
  • Improve API Communication: Ensures clear communication between client and server.
  • Enhance Automated Testing: Used in test validations to verify expected API behavior.
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.

  • Request Body: The request body contains data sent from the client to the API, such as input parameters, user credentials, form data, or JSON/XML payloads. It is commonly used in POST, PUT, and PATCH requests to create or update resources.
    Example: Sending user registration details in a POST request.
  • Response Body: The response body contains data returned by the API to the client, such as requested information, success messages, error details, or status data.
    Example: Returning user profile information in a GET request.
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 testing the vulnerabilities in the API. This is done through penetration testing or manual scanning of the APIs. API security testing is important:

  • Cloud-based applications rely on APIs to exchange data and interact with each other. Any security vulnerabilities can have far-reaching consequences.
  • Online operations and businesses rely on APIs to integrate different systems and services. This causes potential security risks.
  • Organizations rely on security solutions that are built for web apps to detect and secure from API threats. Such solutions cannot detect unique vulnerabilities and gaps in the APIs.

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

BVA tests edge cases of input ranges (e.g., min/max values) to find defects at boundaries.

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

API versioning involves specifying a version number in the API endpoint or headers to ensure the backward compatibility. It manages the changes in the API over time.

  • It ensures the correct version of the API is being tested.
  • It ensures that the changes in the API do not break the existing client applications.

27. What tools could be used for API testing?

  • Katalon: This is easy-to-use tool that supports REST, SOAP requests, and SSL client certificates. It also enables test import from Swagger, Postman, WADL, and WSDL.
  • JMeter: Apache JMeter is an open-source, 100% Java application that is created for performance testing. This tool enables automatic working with CSV files.
  • REST-assured: REST-assured is an open-source Java domain-specific language that enables testing REST services. It supports POST, GET, PUT, DELETE, PATCH, and HEAD requests.
  • SoapUI: SoapUI is an automated testing tool for Soap and REST APIs. It is an open-source tool that allows to create tests effortlessly with drag and drop, point-and-click.
  • Postman: Postman is an application that is used for API testing. It is a standalone platform that is used to build, test, design, modify, and document APIs.

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

Key Considerations When Writing API Documentation

  • Clear API Overview: Explain API purpose, features, and use cases.
  • Endpoint Details: List all endpoints (GET /users, POST /orders) with descriptions.
  • Request & Response Format: Provide JSON/XML examples with expected parameters.
  • Authentication & Security: Explain how to use API keys, OAuth, or JWT for access.
  • Error Handling: Document status codes (400 Bad Request, 500 Internal Server Error) and responses.
  • Rate Limits & Throttling: Define request limits and handling of 429 Too Many Requests.

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

  • GraphQL Testing: Focuses on queries, mutations, and schema validation. Use tools like Postman or Apollo Client to send queries (e.g., { user(id: 1) { name } }) and verify response structures. Test for over-fetching/under-fetching and schema compliance.
  • REST Testing: Tests fixed endpoints (e.g., GET /users/1) with predictable responses. Focus on HTTP methods and status codes.

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

To secure APIs during testing, follow these best practices:

  • Authentication & Authorization: Verify security mechanisms like: OAuth 2.0, JWT (JSON Web Token), API Keys, Basic Auth
  • Input Validation & Sanitization: Prevent SQL Injection and XSS attacks by validating input data.
  • Secure Headers & Encryption: Use HTTPS (TLS/SSL) and set security headers like: Strict-Transport-Security, Content-Security-Policy
  • Rate Limiting & Throttling: Prevent DDoS attacks by limiting API request rates.
  • Token Expiry & Refresh Mechanism: Ensure JWTs expire and implement refresh tokens securely.
  • Access Control (RBAC): Restrict API access based on user roles and permissions.
  • Logging & Monitoring: Track API activity using logging tools for anomaly detection.
  • Automated Security Testing: Use tools like OWASP ZAP, Postman Security Tests, Burp Suite to identify vulnerabilities.

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?

Handling Error Responses in API Testing:

  • Validate HTTP Status Codes: Ensure correct 4xx (client errors) and 5xx (server errors) are returned.
  • Check Error Messages: Verify meaningful, user-friendly error messages.
  • Test Edge Cases: Send invalid inputs, missing parameters, and malformed requests.
  • Implement Retry Mechanism: Retry requests for temporary failures (5xx errors).
  • Monitor & Log Errors: Use tools like Postman, JMeter to track failures.
  • Respect Rate Limits (429): Implement delays or follow Retry-After headers.
  • Secure Error Handling: Ensure no sensitive data is leaked in error responses.

33. What is input validation?

Input validation is the process of verifying user input to ensure it is correct, secure, and meets expected criteria before processing. It helps prevent errors, data corruption, and security vulnerabilities like SQL Injection and XSS attacks. Input validation can be performed on both client-side and server-side for better security and data integrity.

34. Why input validation is important in API testing?

Input validation is important in API testing because it prevents invalid or malicious data from entering the system, helping avoid security vulnerabilities, application errors, and injection attacks.

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

Cross-site request forgery (CSRF) is an attack that forces an authenticated user to perform unwanted actions in a web application without their consent. This attack exploits the trust a web application places in an authenticated user.

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 can be prevented by using security measures such as:

  • CSRF Tokens: Unique random tokens are added to each user session and validated by the server to prevent unauthorized requests.
  • SameSite Cookies: Restrict cookies from being sent with cross-site requests, reducing the risk of CSRF attacks.
  • Referer/Origin Validation: Checks whether the request originated from a trusted domain before processing it.
  • Authentication Headers: Using JWT or access tokens in headers instead of cookies helps prevent CSRF vulnerabilities.

37. What is API contract testing?

API contract testing is a type of testing that aims to monitor the API conversation that takes place between the API consumer and the API producer. It can be performed using tools like Postman, Swagger, etc.

38. Why is API contract testing important?

API contract testing ensures that APIs follow a defined structure (contract) between the client and server, preventing breaking changes.

  • Ensures Consistency: Verifies API responses match the expected format (JSON, XML).
  • Detects Breaking Changes: Prevents issues when updating APIs.
  • Improves Reliability: Ensures backward compatibility across services.
  • Speeds Up Development: Allows frontend and backend teams to work independently.
  • Enhances API Stability: Reduces failures in integrations by enforcing standards.

39. What is API performance testing?

API Performance Testing evaluates an API’s speed, scalability, and reliability under different loads and conditions. It ensures that the API responds efficiently and remains stable under varying traffic levels.

  • Response Time: Measures how quickly the API responds.
  • Throughput: Checks the number of requests handled per second.
  • Load Testing: Simulates high user traffic to check performance.
  • Stress Testing: Determines API behavior under extreme conditions.
  • Spike Testing: Evaluates API response to sudden traffic surges.

40. Why API performance testing important?

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

  • Helps identify bottlenecks and performance issues.
  • Ensures APIs remain stable under high traffic.
  • Improves scalability, reliability, and user experience.
  • Measures response time, throughput, and system behavior under load.

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 ensures that APIs remain reliable, fast, and secure by tracking their performance in real-time.

  • It provide measurements of how long a routine takes to execute, how often it is called, and how much of total time is spent in executing the transaction.
  • It is important to ensure availability, performance, and security of the APIs.
  • It helps to guarantee a dependable and effective user experience.
  • It helps to track the availability of the critical APIs.

43. What is API virtualization?

API virtualization is the process of using a tool that creates a virtual copy of the API mirroring all of the specifications of the production API and using this virtual copy for testing.

  • Allows early testing before the actual API is built.
  • Reduces dependency on live systems by simulating unavailable APIs.
  • Improves development speed by enabling teams to work in parallel.
  • Supports performance testing under various conditions.

44. Why API virtualization is used in API testing?

  • It is used in API testing as it allows for testing much earlier in the development process, removing the key bottlenecks that would otherwise delay production.
  • It is helpful to isolate dependencies, simulate responses, and ensure consistent behavior.

45. What is the purpose of API documentation in API testing?

API documentation is a technical document that describes the API in detail. It includes instructions on how to effectively use and integrate with the API and provides updates regarding API's lifecycle such as new versions. It is the primary resource explaining what is possible with the API and how to get started with the API.

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

  • Critical Functionality First: Focus on core APIs that impact business operations.
  • Frequently Used APIs: Test APIs that are accessed most often by users.
  • Recently Changed or Updated APIs: Prioritize APIs modified in recent updates.
  • APIs with High Bug History: Retest APIs that previously had defects.
  • Security and Authentication APIs: Ensure no vulnerabilities are introduced.
  • Performance-Critical APIs: Validate APIs affecting system speed and scalability.
  • Dependent APIs: Test APIs that interact with multiple services or components.

47. How to handle versioning in API testing?

  • Test Multiple Versions: Ensure backward compatibility by testing old and new API versions.
  • Use Version-Specific Endpoints: Validate API calls with versioned URLs (e.g., /v1/users vs. /v2/users).
  • Check Header-Based Versioning: Verify API responses when versioning is done via headers (Accept: application/vnd.api.v2+json).
  • Compare Responses: Ensure consistency between different versions while testing improvements.
  • Validate Deprecated Features: Test error handling for removed or updated functionalities.
  • Automate Version-Based Tests: Maintain separate test suites for each API version.

48. List the challenges faced while performing API testing.

  • Building irrelevant tests: Building tests without considering how the APIs will be consumed may be quicker in the short term.
  • Initial setup of API testing: Setting up an API testing setup requires certain level of expertise and dedication among the team members.
  • Not including API dependencies: Failure to include API dependencies as a part of API testing strategy can be a critical API testing challenge.
  • Not validating data: It might be possible that API tests pass successfully but APIs are not returning the correct data in their responses.

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

Different Bugs Found in API Testing:

  • Duplicate or missing functionality.
  • Improper messaging.
  • Multi-threading issues.
  • Security and performance issues.
  • Reliability issues.

50. Is it possible to hack API while testing?

Yes, it is possible to hack API while testing as requests are being sent over the internet which mostly follows HTTP protocol which is a text-based protocol. Hence, it is important to perform security testing of the APIs to ensure safer systems.

Common API Vulnerabilities Exploited:

  • Broken Authentication: Weak tokens or missing authentication.
  • SQL Injection: Malicious queries to access or modify databases.
  • Cross-Site Scripting (XSS): Injecting scripts into API responses.
  • Insecure Endpoints: Exposed sensitive data due to improper access controls.
  • Rate Limiting Bypass: Exploiting APIs by sending excessive requests.

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?

The API test environment is a setup where APIs are tested under controlled conditions before deployment. It includes:

  • 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 name and job.
  • Validate the status code and response fields.
  • Use a JSON schema to ensure response structure.
  • Extract and print the 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;

public class PostApiTest {
    @Test
    public void testPostUser() {
        // Set base URI
        RestAssured.baseURI = "https://reqres.in/api";

        // Define request payload
        String requestBody = "{\"name\": \"Alice\", \"job\": \"Engineer\"}";

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

        // Extract and print user ID
        String userId = response.jsonPath().getString("id");
        System.out.println("Created User ID: " + userId);

        // Additional assertion for non-null ID
        Assert.assertNotNull(userId, "User ID is null");
    }
}

Schema File (user-schema.json in src/test/resources):

{
"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

Test passes if status code is 201, response fields match, and schema is valid.

2. Write a Postman script to chain a GET and POST request, passing data dynamically.

Steps:

  • Send a GET request to retrieve user data.
  • Store the user ID in an environment variable.
  • Use the ID in a POST request payload.
  • Validate the POST response.

Code (Postman Pre-request Script for GET):

pm.sendRequest({
url: 'https://reqres.in/api/users/2',
method: 'GET'
}, function (err, response) {
if (!err) {
pm.environment.set("userId", response.json().data.id);
}
});

POST Request Setup:

  • URL: https://reqres.in/api/posts
  • Method: POST
  • Body (raw JSON): {"title": "New Post", "userId": {{userId}}}

Test Script (for POST):

pm.test("POST request with chained userId", function () {
pm.response.to.have.status(201);
var jsonData = pm.response.json();
pm.expect(jsonData.userId).to.eql(parseInt(pm.environment.get("userId")));
console.log("Post created with userId: " + jsonData.userId);
});

Output: Post created with userId: 2

Test passes if status is 201 and userId matches.

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

Steps:

  • Send a DELETE request.
  • Validate the status code (204).
  • Send a GET request to confirm the resource is gone (expecting 404 or empty response).
Java
import io.restassured.RestAssured;
import org.testng.annotations.Test;

public class DeleteApiTest {
    @Test
    public void testDeleteUser() {
        RestAssured.baseURI = "https://reqres.in/api";

        // Send DELETE request
        RestAssured.given()
                .when()
                .delete("/users/2")
                .then()
                .statusCode(204)
                .log().all();

        // Verify resource is deleted (ReqRes is mock, so GET may still return data)
        RestAssured.given()
                .when()
                .get("/users/2")
                .then()
                .statusCode(200); // Mock API limitation, ideally expect 404
    }
}
  Output: [DELETE Response]: 204 No Content

Test passes if DELETE returns 204. Note: ReqRes is a mock API, so GET may not reflect deletion; in real scenarios, expect 404.

4. Write a Postman script to validate API response time and handle rate limiting.

Steps:

  • Send a GET request and validate response time.
  • Simulate rate limiting with repeated requests in a loop.
  • Check for 429 status (mock API may not enforce limits).

Test Script:

pm.test("Response time is under 500ms", function () {
    pm.expect(pm.response.responseTime).to.be.below(500);
    console.log("Response time: " + pm.response.responseTime + "ms");
});

// Simulate rate limiting (mock API may not return 429)
for (let i = 0; i < 60; i++) {
    pm.sendRequest({
        url: 'https://reqres.in/api/users?page=2',
        method: 'GET'
    }, function (err, res) {
        if (res && res.code === 429) {
            pm.test("Rate limit detected", function () {
                pm.expect(res.code).to.equal(429);
            });
        }
    });
}
Output: Response time: 230ms

Test passes if response time is <500ms. Note: ReqRes doesn’t enforce rate limits, so 429 may not occur; real APIs would trigger it.

5. Write a RestAssured script to test a GraphQL API query.

Steps:

  • Construct a GraphQL query as a JSON payload.
  • Send a POST request to the GraphQL endpoint.
  • Validate status and response data.
Java
import io.restassured.RestAssured;
import org.testng.annotations.Test;

public class GraphQLApiTest {
    @Test
    public void testGraphQLQuery() {
        RestAssured.baseURI = "https://graphqlzero.almansi.me/api";

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

        RestAssured.given()
                .header("Content-Type", "application/json")
                .body(query)
                .when()
                .post()
                .then()
                .statusCode(200)
                .body("data.user.name", org.hamcrest.Matchers.equalTo("Geeks Geeks"))
                .log().body();
    }
}

Output:

{
  "data": {
    "user": {
      "name": "Geeks Geeks"
    }
  }
}

Test passes if status is 200 and name is correct.

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:

  • Send a POST request to the token endpoint to get an access token.
  • Use the token in the Authorization header for the GET request.
  • Validate the response.

Code (Using a mock OAuth setup):

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

public class OAuthApiTest {
    @Test
    public void testOAuthRequest() {
        // Mock token endpoint (replace with real endpoint)
        RestAssured.baseURI = "https://auth.example.com";
        Response tokenResponse = RestAssured.given()
                .formParam("grant_type", "client_credentials")
                .formParam("client_id", "your_client_id")
                .formParam("client_secret", "your_client_secret")
                .when()
                .post("/token")
                .then()
                .statusCode(200)
                .extract()
                .response();

        String accessToken = tokenResponse.jsonPath().getString("access_token");

        // Use token for API request
        RestAssured.baseURI = "https://api.example.com";
        RestAssured.given()
                .header("Authorization", "Bearer " + accessToken)
                .when()
                .get("/data")
                .then()
                .statusCode(200)
                .log().body();
    }
}

Output: [Response]: {"data": "Sample data"}

Test passes if GET request succeeds with 200. Note: Replace mock endpoints/credentials with real ones.

8. Write a Postman script to perform negative testing on a POST API.

Steps:

  • Send a POST request with an invalid payload.
  • Validate status code and error message.

POST Request Setup:

  • URL: https://reqres.in/api/users
  • Method: POST
  • Body (raw JSON): {"job": "Engineer"} (missing name)

pm.test("Negative test for missing name", function () {
pm.response.to.have.status(400);
var jsonData = pm.response.json();
pm.expect(jsonData.error).to.include("Missing name");
console.log("Error: " + jsonData.error);
});

Output:

Error: Missing name

Test passes if status is 400 and error message is correct. Note: ReqRes may not return specific errors; real APIs should.

Comment

Explore