API testing ensures that APIs function correctly in functionality, performance, security, and reliability. Unlike UI testing, which focuses on appearance, API testing verifies backend operations. With APIs being crucial in modern software, mastering API testing is essential for QA professionals. Companies like Google, Facebook, and Amazon prioritize API testing for high software standards.
This interview guide covers the most asked API Testing Interview Questions for beginners and experienced professionals (3, 5, and 8 years). It includes REST vs. SOAP, testing tools, authentication, performance testing, and Postman examples to help you excel in API testing interviews
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 processRead More - API Testing.
2. What is an API and Types of APIs?
An Application Programming Interface (API) is useful for communication between different software systems. It acts as an interface between two applications and allows two software systems to communicate with one another.
APIs (Application Programming Interfaces) allow different software systems to communicate with each other.
- Web APIs: A Web API (also known as Web Service) is one of the most common types of APIs. It works over the internet and follows HTTP protocols. Web APIs are open-source, meaning they can be accessed by multiple clients like phones, tablets, or computers to exchange data.
- Local APIs: Local APIs allow applications within the same system to communicate with each other. Developers use them for middleware services—software that connects different applications.
- Program APIs: Program APIs help one software program interact with another, even if they are not on the same system. They often use Remote Procedural Calls (RPCs) to make a remote program appear as if it’s running locally.
Read More - API.
3. What is the difference between REST and SOAP APIs?
- REST: Lightweight, uses HTTP methods (GET, POST), stateless, and returns JSON/XML.
- SOAP: Protocol-based, uses XML, and supports complex operations with WS-Security.
SOAP API | REST API |
Relies on SOAP (Simple Object Access Protocol) | Relies on REST (Representational State Transfer) architecture using HTTP. |
Transports data in standard XML format. | Generally transports data in JSON. It is based on URI. Because REST follows a stateless model, REST does not enforce message format as XML or JSON etc. |
Because it is XML based and relies on SOAP, it works with WSDL | It works with GET, POST, PUT, DELETE |
Read More - SOAP API Vs. REST API.
4. Mention Common HTTP Methods used in API Testing.
Here are the Common HTTP Methods used in 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.
Read More - HTTP Methods of API Testing.
5. 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.
6. 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.
Read More - Postman for API Development.
7. List the differences between API and Web Service.
Here is the Differences between Web Services and Web API:
Parameters | API | Web Service |
---|
Definition | API is an Application Programming Interface that acts as an interface between two applications. | Web services are a type of API that must be accessed through a network connection. |
---|
Protocols Support | It provides support for HTTP/s protocol. | It provides support for HTTP protocol. |
---|
XML Support | API supports XML and JSON. | Web service supports XML. |
---|
Read More - Web Services Vs. Web API.
8. 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 RESTful APIs, ensuring secure and structured web communication.
- SOAP (Simple Object Access Protocol): A protocol that uses XML-based messaging for web services.
- REST (Representational State Transfer): A widely used web service architecture over HTTP.
- GraphQL: A query language for APIs that allows fetching specific data efficiently.
- WebSockets: For real-time communication between a client and a server
9. Tell me Advantages and Disadvantages of API Testing.
Advantages:
- Faster bug fixes: API testing works quickly to provide a solution, thus it helps to diagnose problems earlier in the development of the system allowing for efficient bug detection and removal.
- Reduced costs: API testing provides quick release of results, easier to maintain, thus reducing the cost of testing.
- Universal 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.
Dis-advantages:
- Technical skills: API testing requires skilled and trained testers
- Time-consuming: API testing is time-consuming as it requires time to develop and execute test scripts for APIs.
- Limited documentation: Limited documentation of the API makes it difficult for the testers to understand how the API should behave in response to a particular input.
10. List the differences between API Testing and Unit Testing.
Here is the Differences between API Testing and 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. |
---|
Type testing | It is mostly Black-box testing. | It is White-box testing. |
---|
Read More - API Testing Vs. Unit Testing.
11. 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).
12. 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.
13. 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: JSON Web Tokens for secure, stateless access.
- Basic Auth: Base64-encoded username:password in headers.
14. 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.
Read More - Test Case For API Testing.
15. What is the difference between a GET and POST request?
- GET: Retrieves data, idempotent, parameters in URL.
- POST: Creates data, non-idempotent, data in request body.
Read More - GET Vs. POST Request.
Headers provide metadata about the request/response, such as content type, authorization, or caching instructions.
17. 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.
18. What is Negative Testing in the context of APIs?
Negative testing validates API behavior with invalid inputs, such as incorrect data or unauthorized requests, to ensure proper error handling.
Read More - Negative testing.
19. What is the purpose of authentication in API testing?
API authentication is a combination of technology or process that verifies the identities of users who want access to an API. It involves the use of software protocol to verify identity of the requester before granting access to protected resources.
Authentication verifies the identity of a user or system. Common methods include API keys, OAuth, JWT (JSON Web Tokens), and Basic Auth.
Read More - API Authentication.
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 ?.
These questions focus on practical automation, scripting, and intermediate concepts for testers.
21. What is API mocking and Why is used ?
API mocking is practice of simulating the behavior of an API endpoint during testing without actually invoking the real API. It is beneficial during the development stage.
- Request Headers: Provide metadata about the request, such as authentication (Authorization), content type (Content-Type), and caching control.
- Response Headers: Contain metadata about the server response, including status info, content type, and security policies.
Here are the reasons why it is used:
- Mock APIs are useful when applications have dependencies with external APIs.
- Mock APIs are useful for testers to plan and validate test executions and for developers to do unit testing and identify the initial development stages.
- Mock APIs are useful in situations where the complete API needs to be made available for consumer testing before committing it to development stage
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.
Read More -HTTP status codes.
23. What is the purpose of the request and response body in API testing?
The request body is used to send and receive data such as input parameters, or data to create/ update resources via the REST API. The response body is the data API send to the client.
- Request Body: Contains data sent by the client to the API (e.g., user credentials, form data, JSON payload). Example: Sending user details in a POST request.
- Response Body: Contains data returned by the API, such as success messages, error details, or requested information. Example: Returning user profile details in a GET request.
Read More - HTTP Request & Responses.
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.
Read More - Security Testing.
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.
Read More - BVA.
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 tools 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 andXSS 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 likeOWASPZAP, 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 customer 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.
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.
Input validation is important in API testing as it prevents malicious data from entering the system. It is important to prevent injection attacks and other malicious activities. This can be done manually or using automated tools.
35. What is cross-site request forgery (CSRF)?
Cross-site request forgery is an attack that forces user top execute unwanted action in the web application in which they are authorized to perform actions. This attack exploits the trust the web application has in an authenticated user.
Read More - Cross-site request forgery.
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 tokens: CSRF can be prevented by using CSRF tokens. These are the random tokens that need to be unique per user session and should be of large random value to make it difficult to guess.
- SameSite cookies: SameSite is a browser security mechanism that determines when a website's cookies are included in the requests originating from other websites.
- Referer-based validation: HTTP referer header can be used to defend against CSRF attacks by verifying the request originated from the application's own domain.
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 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.
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.
API performance testing ensures that an API is fast, scalable, and reliable under different workloads.
- API performance testing helps to improve the API's overall performance and stability.
- It helps to provide insight into the API's overall performance thus helping to identify the areas of strength and weakness.
- It helps to identify the performance issues and determine the impact of changes.
- It helps to ensure that the API is flexible and can handle the demands of the real world.
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.
Read More - API monitoring.
42. Why API monitoring important?
API monitoring ensures that APIs remain reliable, fast, and secure by tracking their performance in real-time.
- They 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 API and provides updates regarding API's lifecycle such as new versions. It is 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.
- Building irrelevant tests: Building tests without considering how the APIs will be consumed may be quicker in 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.
API load testingis 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.
Read More - 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.
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.
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
guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Thread Group">
name="ThreadGroup.on_sample_error" elementType="Argument">
name="Argument.value">continue
name="ThreadGroup.num_threads">50
name="ThreadGroup.ramp_time">10
name="ThreadGroup.scheduler">true
name="ThreadGroup.duration">30
guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Request">
name="HTTPSampler.domain">reqres.in
name="HTTPSampler.path">/api/users?page=2
name="HTTPSampler.method">GET
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.
Conclusion
API testing ensures functionality, security, and performance in modern applications. This guide covered key interview questions, best practices, and essential tools for beginners and experienced professionals. Mastering API testing helps improve software reliability and prepares you for real-world challenges.
API Testing Interview Questions for 2025: Top 50 Interview Questions
Similar Reads
Top HR Interview Questions and Answers (2025) HR interviews can be daunting but they donât have to be. The bottom line in most hiring processes entails testing the personality of a candidate for their communication traits and company culture fit. Being at the initial or experienced levels of your career being prepared for commonly asked fresher
15+ min read
Common Interview Questions and Preparation Guide for 2024 A peal of nervous laughter, an anxious candidate aspiring for the job of their dreams. We've all been there at some point in our lives. These Common Interview Questions and Preparation guide will help you in your next interview.In this article we covered how to answer of particular generic questions
5 min read
Amdocs Interview Questions Amdocs is a global leader in software and services for communications, media, and financial services providers that stands at the forefront of technological transformation. Their solutions empower businesses to navigate the rapidly evolving digital landscape, optimize operations, and deliver seamles
5 min read
Accenture Interview Questions Accenture is one of the leading global professional services companies, renowned for its capabilities in digital, cloud, and security services. Securing a position as a developer at Accenture is highly competitive, requiring candidates to demonstrate a blend of technical prowess, problem-solving ski
2 min read
Technical Interview Questions Technical interviews are a crucial part of the hiring process for many tech companies like Amazon, Microsoft, Cisco, Google, Facebook, etc. as they test your technical skills, knowledge, and problem-solving abilities. The purpose of a technical interview is to test how you solve real-world problems,
5 min read
GreyOrange Interview Questions Check out these handpicked GreyOrange interview questions to help you get ready for a successful career move with this cool robotics and automation company. Learn about the types of questions they might ask in technical assessments and problem-solving situations. Get ready to shine in your interview
4 min read
Top 25 Frequently Asked Interview Questions in Technical Rounds Here is the collection of the TOP 25 frequently asked questions based on the experience of interviews in multiple companies. 1Lowest common Ancestor2An unsorted array of integers is given; you must find the max product formed by multiplying three numbers. (You cannot sort the array, watch out when t
1 min read
Publicis Sapient Interview Questions Explore Publicis Sapient Interview Questions for an insight into this global digital transformation consultancy. Headquartered in Boston, Massachusetts, USA Publicis Sapient is leading in reshaping the digital business landscape. With a commitment to meaningful change, they operate at the nexus of t
4 min read
PhonePe Interview Questions Explore this carefully selected collection of PhonePe interview questions, offering insights to help you prepare for a successful career move with this innovative digital payment and financial technology company. Uncover the various questions that PhonePe might present during technical assessments a
4 min read
CGI Interview Experience 2021 The interview process includes 3 rounds. The technical skills include Java 8, Spring boot, Hibernate, and Microservices. Round 1: This round took 45 minutes Coding question on string reversal without using built-in operations.Technical questions on java8 concepts steam, lambda Expressions, Default m
1 min read