Rest Api Testing Interview questions and answers
Rest Api Overview
REST (Representational State Transfer) API is a set of architectural principles used for building web services that are scalable, flexible, and interoperable. It relies on a client-server architecture where communication occurs over HTTP protocols.
In REST, resources are the key abstraction, representing any information that can be accessed via a unique identifier (URI). These resources can be manipulated using standard HTTP methods such as GET, POST, PUT, DELETE, which correspond to CRUD (Create, Read, Update, Delete) operations.
REST APIs use stateless communication, meaning each request from the client contains all the necessary information for the server to fulfil it, without relying on any previous interactions. Responses are typically in formats like JSON or XML, making them easy to parse and process.
Overall, REST APIs provide a uniform interface for accessing and manipulating resources over the web, enabling seamless integration between different systems and applications.
Rest Api Testing Interview Q & A
1. What are the HTTP Methods Rest API provides?
2. What is the difference between PUT and PATCH?
{ “id” : “1”, “name” : “techsavvy4u”, “email” : “user@techsavvy4u.com”, “address” : “address1”, “type” : “vendor” }
3. Which scenarios HEAD and OPTIONS are useful?
OPTIONS – suppose if we don’t know if DELETE and update via PUT is available for a resource, we can use this
HEAD – Checking if resource is changed, this is required especially when maintaining cached version of resource. And also when before making possibly costly retrieval checking media type and size would be useful.
4. What is URI in rest API?
URI is Uniform resource identifier, it’s a string which identifies the resource on a webserver.
5. What is Authentication and authorization?
- Authentication – verifying the identity of a client trying to access a resource.
- Authorization – determines what actions a user is allowed to perform. Once a user has been authenticated, authorization mechanisms ensure that the authenticated user has the necessary permissions to access or modify specific resources. Authorization is usually implemented through roles, permissions, or policies assigned to authenticated users. For example, an admin user might have permission to perform actions that a regular user does not.
6. What are the different Authentication mechanism available in rest api?
- Basic Authentication : This involves sending a username and password with each request, typically in the form of an HTTP header.
- Token-based Authentication : Instead of sending credentials with every request, a token is generated upon successful authentication and sent back to the client. The client then includes this token with subsequent requests.
- OAuth : OAuth is an open-standard authorization protocol that allows users to provide third-party applications limited access to their resources without revealing their credentials. OAuth involves authentication as well as authorization.
- JSON Web Tokens (JWT) : JWT is a compact, URL-safe means of representing claims to be transferred between two parties. It’s commonly used for authentication by securely transmitting information between parties as a JSON object.
7. What is headers in rest api? What kinds of information is passed?
headers in HTTP request and response messages, carry additional information about the request or response. Headers contain metadata about the data being transmitted and provide various instructions or details to the client or server. There are several types of headers, each serving a specific purpose:
Request Headers : These headers are included in the HTTP request sent by the client to the server. Some common request headers include:
-
- Authorization: Contains credentials or tokens used for authentication, such as Basic Authentication credentials or JWT tokens.
- Content-Type: Specifies the MIME type of the request body, indicating the format of the data being sent (e.g., application/json, application/xml).
- Accept: Informs the server about the preferred MIME types of the response content that the client can handle.
- User-Agent: Provides information about the client making the request, such as the user’s browser or application version.
- Cookie: Contains cookies associated with the request, allowing the server to maintain session state or track user preferences.
- Cache-Control: Specifies caching directives to control how the request/response can be cached by intermediaries (e.g., proxies, caches).
Response Headers: These headers are included in the HTTP response sent by the server to the client. Some common response headers include:
-
- Content-Type: Indicates the MIME type of the response body, informing the client about the format of the data being returned.
- Cache-Control: Instructs the client and intermediaries on how to cache the response to optimize future requests.
- Set-Cookie: Sets a cookie on the client’s browser, enabling the server to maintain session state or store user-specific data.
- Location: Used in redirection responses (e.g., HTTP 3xx status codes) to indicate the URL to which the client should redirect.
- Access-Control-Allow-Origin: Specifies which origins are allowed to access the resource in cross-origin requests (CORS).
- ETag: Provides a unique identifier for the response, allowing clients to perform conditional requests and cache validation.
8. What are the different content types supported by rest api?
Some commonly supported content types in REST APIs include:
JSON (JavaScript Object Notation).
XML (Extensible Markup Language)
Plain Text
HTML (Hypertext Markup Language)
Form Data
Binary Data: REST APIs can also transmit binary data, such as images, videos, or documents, using content types like image/jpeg, application/pdf, or application/octet-stream. Binary data is typically encoded using base64 or other encoding schemes to ensure compatibility with HTTP protocols.
Message Pack
CSV (Comma-Separated Values)
Protocol Buffers.
9. What is path param, query params and explain how are they different from each other?
Path parameters and query parameters are both used to pass information to the server, but they are used in different ways and have distinct purposes.
Path Parameters:
-
- Path parameters are part of the URL path itself and are used to identify a specific resource or endpoint.
- They are typically denoted by placeholders within the URL path, enclosed in curly braces {}.
- Path parameters are used to define variable parts of the URL that correspond to dynamic data, such as IDs, names, or slugs.
- Example: In the URL /users/{userId}, {userId} is a path parameter that represents the unique identifier of a user resource.
- Path parameters are essential for specifying the target resource directly in the URL, making the endpoint more descriptive and RESTful.
Query Parameters:
-
- Query parameters are appended to the URL as key-value pairs and are separated from the base URL by a question mark ?.
- They are used to provide additional information to the server or to filter, sort, or paginate resources.
- Query parameters consist of a key (parameter name) and a value, separated by an equals sign =. Multiple query parameters can be included by separating them with ampersands &.
- Example: In the URL /users?role=admin&status=active, role and status are query parameters with values admin and active, respectively.
- Query parameters are optional and can be used to modify the behavior of the API request without affecting the URL structure or resource identification.
10. What is request and response body?
Request body is part of HTTP request sent from client to server. Not all methods need to have request body. Typically, GET and DELETE requests will not have request body.
Other requests like POST, PUT, PATCH will have request body specifying what data the resource needs to be created, updated.
Response body is part of HTTP response sent from server to client. It contains the data returned by the server in response to the client’s request
For successful responses, the response body often contains the requested resource’s data or a confirmation message. For error responses, it may include error details or additional context.
11. Can I send request body in GET and DELETE?
GET method: According to the HTTP specification, the GET method should not include a request body. GET requests are intended to retrieve data from the server and should only contain parameters in the URL. While technically possible, sending a request body with a GET request is not standard practice and can lead to interoperability issues.
DELETE method: The DELETE method, like GET, typically does not include a request body. DELETE requests are used to instruct the server to remove a resource identified by the request URL. While the HTTP specification does not explicitly forbid a request body in DELETE requests, it is generally not recommended as it goes against the standard semantics of the method and may not be supported by all server implementations and APIs.
In both cases, adhering to standard conventions and best practices helps maintain clarity, predictability, and interoperability in API design.
12. What are the different error status codes in rest response?
- 1xx – Informational messages
- 2xx – Success
- 3xx – Redirection
- 4xx – Client error
- 5xx – Server error
13. What is Idempotent, which http methods are idempotent?
Idempotent operations produce the same result regardless of how many times they are executed. The idempotent HTTP methods are GET, HEAD, PUT, and DELETE.
POST is not idempotent because each execution of a POST request can result in a different outcome, such as creating a new resource or modifying existing ones. Multiple identical POST requests may result in the creation of multiple resources, leading to different states on the server.
14. What is API versioning and why is important to test that?
API versioning is the practice of managing changes to an API over time by assigning unique identifiers to different releases or iterations. It’s important to test API versioning to ensure backward compatibility with existing clients, validate the functionality of new features, prevent regressions, and maintain consistent behavior across different versions.
- URL Path Versioning – /api/v1/resource or /api/v2/resource.
- Query Parameter Versioning: /api/resource?version=1
- Header Versioning: a custom HTTP header, such as Accept-Version: 1
- Content Negotiation: Use content negotiation mechanisms to specify the desired API version in the Accept header of the request.
- Subdomain Versioning: Include the version information as a subdomain in the URL, such as v1.api.example.com/resource.
- Media Type Versioning: Define different media types for different API versions, such as application/vnd.example.v1+json
15. what specific aspects would you focus on to ensure that a REST API adheres to best practices?
Look for the following things when reviewing or doing test planning.
- Use meaningful and descriptive resource URIs.
- Follow standard HTTP methods for CRUD operations.
- Use nouns for resource endpoints and avoid verbs.
- Maintain consistency in naming conventions.
- Support versioning to manage API changes.
- Implement proper error handling and provide informative error messages.
- Use appropriate status codes to indicate the outcome of requests.
- Secure sensitive endpoints with proper authentication and authorization mechanisms.
- Optimize endpoint performance through pagination, caching, and compression.
- Document endpoints thoroughly to facilitate API usage and integration.
16. API mocking and what is the importance of API mocking?
API mocking ultimately ensures thorough, efficient, and cost-effective testing of client applications, enhancing quality and reliability before deployment.
- Early Testing: API mocking enables testing client applications before the actual APIs are fully developed or available, facilitating early validation and parallel progress in development and testing.
- Parallel Development: Mock APIs facilitate independent development of client applications, decoupling from backend API readiness, enabling faster iterations without waiting for dependencies.
- Isolation: Mocking API responses isolates testing from external dependencies like backend systems, ensuring focused testing of client-side logic unaffected by changes in external services.
- Controlled Testing Environment: Mock APIs create controlled environments to simulate various scenarios, edge cases, and errors, verifying client application behavior comprehensively.
- Speed and Efficiency: Testing with mock APIs is faster and more efficient than real APIs, as mock responses are instant without network latency or backend processing overheads.
- Test Automation: Mock APIs integrate seamlessly into automated testing frameworks, enabling repeatable and consistent testing for enhanced coverage and reliability.
- Scenario Testing: Mocking APIs allows simulation of specific scenarios or conditions, such as error responses or timeouts, challenging to replicate with real APIs.
- Cost Savings: Using mock APIs reduces the need for real backend systems, saving costs on accessing and maintaining them, especially when real API usage incurs fees or infrastructure costs.
17. What kind of load testing to do for API?
Stress Testing: Apply excessive load to the API to determine its breaking point and identify performance bottlenecks under extreme conditions.
Volume Testing: Test the API’s scalability and throughput by simulating a large volume of concurrent requests over an extended period.
Endurance Testing: Continuously apply a consistent load to the API over time to evaluate its stability, memory leaks, and performance degradation.
Spike Testing: Simulate sudden spikes in traffic to assess the API’s response to abrupt increases in request volume and validate auto-scaling mechanisms.
Soak Testing: Apply sustained load to the API for an extended duration to detect memory leaks, resource exhaustion, or degradation in performance.
Concurrency Testing: Evaluate the API’s efficiency in handling multiple concurrent connections or requests without excessive contention.
Peak Load Testing: Test the API’s performance during peak usage times to ensure it can handle high loads without performance degradation.
Failover Testing: Simulate failures in backend services to assess the API’s resilience and ability to handle errors gracefully.
you can identify performance issues, scalability limitations, and bottlenecks in the API infrastructure, allowing you to optimize performance, enhance reliability, and ensure a smooth user experience under high load conditions.
18. What type of security testing to be done for API testing?
- Authentication Testing: Verify the effectiveness of authentication mechanisms in ensuring that only authorized users can access the API and its resources.
- Authorization Testing: Assess whether access controls are properly implemented to restrict users’ actions and access to resources based on their permissions.
- Data Validation Testing: Validate that input data is properly validated and sanitized to prevent injection attacks, such as SQL injection or XSS.
- Session Management Testing: Test the management of user sessions and tokens to ensure they are securely generated, transmitted, and invalidated after logout or timeout periods.
- Encryption Testing: Ensure that sensitive data transmitted between client and server is encrypted using secure protocols (e.g., TLS/SSL) to prevent eavesdropping or data interception.
- API Rate Limiting Testing: Verify that rate limiting mechanisms are in place to prevent abuse or misuse of the API, protecting against denial-of-service (DoS) attacks.
- Error Handling Testing: Assess the API’s error handling mechanisms to ensure that error messages do not reveal sensitive information and that they provide helpful guidance without exposing vulnerabilities.
- Security Headers Testing: Check for the presence and effectiveness of security headers (e.g., Content Security Policy, X-Content-Type-Options) to mitigate common security risks.
- Injection Testing: Test for injection vulnerabilities, such as SQL injection or XML/JSON injection, by injecting malicious input to manipulate API behavior or access unauthorized data.
- Cross-Origin Resource Sharing (CORS) Testing: Evaluate CORS policies to ensure that they are correctly configured to prevent unauthorized cross-origin requests and protect against cross-site request forgery (CSRF) attacks.
- Third-Party Integration Testing: Assess the security of third-party integrations and dependencies to ensure they do not introduce vulnerabilities or compromise the API’s security posture.
Compliance Testing: Validate that the API complies with relevant security standards, regulations, and industry best practices (e.g., OWASP API Security Top 10, GDPR, HIPAA).
19. GET rest endpoint, what test cases can you think of writing?
Positive Test Cases:
- Verify that the endpoint returns the correct resource(s) when provided with valid input parameters.
- Test with various valid combinations of query parameters to ensure they are processed correctly.
- Check if the response status code is 200 (OK) and the expected resource data is returned in the response body.
Negative Test Cases:
- Attempt to access the endpoint without required authentication credentials and verify that access is denied (401 Unauthorized or 403 Forbidden).
- Test with invalid query parameters or malformed URLs to ensure the endpoint handles them gracefully (e.g., returns 400 Bad Request).
- Verify that the endpoint returns an appropriate response (e.g., 404 Not Found) when requesting a resource that does not exist.
Boundary Test Cases:
- Test with the maximum and minimum allowed values for any parameters (e.g., limit, offset) to ensure the endpoint behaves as expected.
- Verify the behavior of the endpoint when accessing resources at the beginning, middle, and end of a large dataset.
Performance Test Cases:
- Measure the response time of the endpoint under normal load conditions to ensure it meets performance requirements.
- Conduct load testing by sending multiple concurrent requests to the endpoint and verifying that it responds within acceptable time limits.
Security Test Cases:
- Test for potential security vulnerabilities such as SQL injection or XSS by injecting malicious input into query parameters.
- Check if the endpoint exposes sensitive information in error messages or response headers.
Caching Test Cases:
- Verify caching behavior by sending multiple requests with the same parameters and checking if subsequent requests are served from cache.
- Test cache control headers to ensure they are correctly set to control caching behavior.
Cross-Origin Resource Sharing (CORS) Test Cases:
- Verify that CORS headers are correctly configured to allow or restrict cross-origin requests as intended.
- Test with different origin domains to ensure CORS policies are enforced properly.
Documentation Test Cases:
- Verify that the endpoint documentation accurately describes the endpoint’s purpose, input parameters, expected output, and any special behaviors.
- Check if the documentation provides clear examples of how to use the endpoint and interpret the response.
20. Can you give test cases for POST endpoint?
- Positive Test Cases: Verify successful creation of a new resource with valid input data and correct status code (201 Created).
- Negative Test Cases: Test handling of unauthorized access and validation of invalid input data, returning appropriate error responses (e.g., 401 Unauthorized, 400 Bad Request).
- Boundary Test Cases: Test behavior with maximum and minimum input values to ensure correct handling and boundary validation.
- Performance Test Cases: Measure response time and conduct load testing to ensure acceptable performance under normal and peak loads.
- Security Test Cases: Test for security vulnerabilities and data protection measures, such as input sanitization and protection against injection attacks.
- Idempotent Test Cases: Verify that multiple identical POST requests result in the creation of a single resource and proper handling of duplicate requests.
- Error Handling Test Cases: Test handling of various error scenarios to ensure informative error messages and correct status codes are returned.
- Documentation Test Cases: Verify accuracy and completeness of endpoint documentation, including input data format, expected output, and error handling examples.
21. Can you list down testcases to test error responses?
Testing error response scenarios ensure that RESTful API behaves correctly and provides informative error messages to clients, helping users troubleshoot issues effectively.
- Invalid Endpoint: Verify that accessing an invalid or non-existent endpoint returns the appropriate HTTP status code (e.g., 404 Not Found).
- Invalid HTTP Method: Test sending a request with an unsupported HTTP method to an endpoint and ensure that the server returns a 405 Method Not Allowed response.
- Missing Required Parameters: Test sending a request with missing required parameters and verify that the server responds with a 400 Bad Request status code and an informative error message indicating the missing parameters.
- Invalid Parameter Values: Test sending a request with invalid parameter values (e.g., non-numeric value for a numeric parameter, invalid email format) and ensure that the server returns a 400 Bad Request status code with an appropriate error message.
- Unauthorized Access: Verify that accessing a resource without proper authentication or authorization credentials results in a 401 Unauthorized or 403 Forbidden response, depending on the specific scenario.
- Expired or Invalid Tokens: Test sending a request with an expired or invalid authentication token and ensure that the server returns a 401 Unauthorized or 403 Forbidden response, with a message indicating the reason for the authentication failure.
- Rate Limit Exceeded: If the API has rate limiting mechanisms in place, test sending requests exceeding the rate limit and verify that the server responds with a 429 Too Many Requests status code and includes information about the rate limit in the response headers or body.
- Server Errors: Test scenarios where the server encounters internal errors (e.g., database connection failure, server-side validation errors) and ensure that the server returns a 500 Internal Server Error status code along with a meaningful error message to aid debugging.
- Validation Errors: Test scenarios where the server rejects requests due to validation errors (e.g., input length exceeds maximum allowed length, invalid data format) and verify that the server returns a 422 Unprocessable Entity status code with details about the validation errors in the response body.
- Conflict Errors: Test scenarios where the requested action conflicts with the current state of the resource (e.g., attempting to create a resource with a duplicate identifier) and ensure that the server returns a 409 Conflict status code along with information about the conflict in the response body.
- Timeout Errors: Verify that the server responds within an acceptable time frame under normal conditions. This establishes a baseline for comparison with timeout scenarios.
22. What are the tools used to test rest API?
Though the commonly used tools are Postman, Swagger (OpenAPI), SaopUI, RestAssured and Curl here is the list. Pick few from the below list depending on what you have worked on.
- Postman: A versatile API testing tool that allows you to create and execute HTTP requests, automate testing workflows, and analyze responses. It offers features such as request chaining, test scripting, and collection sharing.
- Swagger (OpenAPI): Swagger provides a suite of tools for designing, documenting, and testing REST APIs. It allows you to define API specifications using the OpenAPI Specification and generate interactive API documentation and client SDKs.
- SoapUI: Originally designed for SOAP web services, SoapUI also supports testing of REST APIs. It offers features such as functional testing, load testing, and security testing, with support for scripting and automation.
- REST Assured: A Java-based library for testing REST APIs, REST Assured allows you to write expressive, readable tests using a fluent API. It integrates well with popular Java testing frameworks like JUnit and TestNG.
- JUnit/TestNG: These are popular unit testing frameworks for Java that can be used to write and execute tests for REST APIs. They provide features such as assertion libraries, parameterized tests, and test suite management.
- Curl: A command-line tool for making HTTP requests, Curl is widely used for testing REST APIs manually or in automated scripts. It supports various authentication methods, SSL/TLS, and custom headers.
- Katalon Studio: An all-in-one test automation solution, Katalon Studio supports testing of web services, including REST APIs. It provides a user-friendly interface for creating and executing API tests without coding.
- RestSharp: A popular library for testing REST APIs in .NET, RestSharp simplifies API testing in C# projects by providing a fluent interface for making HTTP requests and handling responses.
- Apache JMeter: While primarily known for load testing web applications, JMeter also supports testing of REST APIs. It allows you to create and execute performance tests, monitor server performance, and analyze test results.
- Httpie: A command-line HTTP client that provides a more user-friendly alternative to Curl. Httpie allows you to make HTTP requests with JSON support, syntax highlighting, and other useful features.
Click here for Postman interview questions for rest API testing.
23. What is API contract testing and why is it important?
API Contract Testing is a type of testing that focuses on ensuring that an API behaves as expected based on a predefined contract or specification. The contract is essentially a formal agreement that defines how the API should communicate, including details such as:
- Endpoints (URIs)
- HTTP methods (GET, POST, PUT, DELETE, etc.)
- Request and response formats (e.g., JSON, XML)
- Data types (strings, numbers, objects)
- Required and optional fields
- Status codes (e.g., 200 OK, 404 Not Found, 500 Internal Server Error)
Contract testing is important as it
- Prevents Integration Issues: Ensures API providers and consumers are aligned, avoiding communication mismatches.
- Improves Reliability and Stability: Guarantees APIs function consistently, even with changes, enhancing service reliability.
- Facilitates Clear Communication: Provides a clear API specification for better collaboration between teams or external partners.
- Enforces Backward Compatibility: Ensures that changes don’t break existing API consumers.
- Early Detection of Bugs: Catches contract violations early in development, preventing issues in production.