- Why API Testing?
API testing is important for a variety of reasons:
- Ensures Functionality: API testing helps ensure that the API is functioning as intended and that it is delivering the expected results.
- Detects Errors: API testing can help detect errors or bugs in the API before they cause problems in the application that uses it.
- Increases Security: API testing can help ensure that the API is secure and that it is not vulnerable to attacks.
- Saves Time and Cost: API testing can save time and cost by identifying issues early in the development cycle, reducing the time and resources required to fix them later.
- Facilitates Collaboration: API testing can help facilitate collaboration between developers and testers, as it enables them to work together to ensure the API meets the requirements and specifications.
- Provides Reliable Documentation: API testing can help ensure that the documentation for the API is accurate and up-to-date, which can be critical for developers and other stakeholders who rely on it.
Overall, API testing is an essential part of software testing that helps ensure that the API meets the requirements and specifications and performs as expected.
- Is there any difference between SOAP and REST API testing? If so, how?
Here are some of the key differences:
- Protocol: SOAP (Simple Object Access Protocol) and REST (Representational State Transfer) are different protocols. SOAP is based on XML, while REST is based on HTTP.
- Data Format: SOAP uses XML for data exchange, while REST uses various formats such as JSON, XML, and plain text.
- Communication: SOAP uses the request-response model, while REST uses the client-server model.
- Complexity: SOAP is generally considered more complex than REST due to its use of XML and the WS-* standards. REST is simpler and easier to use.
- Error Handling: SOAP has standardized error handling, while REST has more flexible error handling.
- Security: SOAP has built-in security features such as WS-Security, while REST relies on HTTPS and other security protocols.
When it comes to testing, both SOAP and REST APIs require different testing approaches due to their differences in protocol, data format, and communication. For example, SOAP API testing requires testing the WSDL (Web Service Description Language) file, while REST API testing requires testing the HTTP methods and URI (Uniform Resource Identifier) endpoints. Additionally, SOAP API testing may require more detailed testing of the XML structure and schema, while REST API testing may require more focus on testing the JSON payload and data formats.
Overall, while SOAP and REST APIs have similarities in terms of their purpose, there are significant differences between the two in terms of protocol, data format, and communication, which impact how they are tested.
- Key things you test in an API – let’s say a GET API to fetch a list of 5 records with id and name
When testing a GET API that fetches a list of 5 records with id and name, here are some of the key things to test:
- Response Status Code: Verify that the HTTP response status code returned by the API is correct. In this case, a successful response should return a 200 OK status code.
- Response Body: Verify that the response body contains the expected data, including the 5 records with their corresponding ids and names.
- Data Format: Verify that the data format used in the response body (JSON, XML, etc.) is correct and valid.
- Pagination: If the API supports pagination, verify that it is functioning correctly and returning the correct number of records.
- Sorting: If the API supports sorting, verify that it is functioning correctly and returning the records in the correct order.
- Error Handling: Verify that the API is handling errors correctly, including returning appropriate error messages and status codes if an error occurs.
- Performance: Verify that the API is responding within an acceptable time frame and is not causing performance issues.
- Security: Verify that the API is secured and not vulnerable to common security threats such as SQL injection or cross-site scripting attacks.
Overall, testing a GET API involves verifying that it returns the expected data in the expected format, handles errors appropriately, and is functioning correctly in terms of performance and security.
- GET vs POST
GET and POST are two of the most commonly used HTTP methods in web APIs. Here are the main differences between them:
Purpose: GET is used to retrieve data from a web server, while POST is used to submit data to be processed by a web server.
Data Transfer: GET sends data in the URL query parameters, which can be visible in the URL and cached by the browser, while POST sends data in the request body, which is not visible in the URL and not cached by the browser.
Data Size: GET has a limit on the amount of data that can be sent (typically up to 2048 characters), while POST has no such limit.
Safety: GET is considered a safe method, meaning it does not modify data on the server, while POST is considered an unsafe method because it can modify data on the server.
Idempotency: GET is an idempotent method, meaning that making the same request multiple times will not result in different outcomes, while POST is not idempotent, meaning that making the same request multiple times can result in different outcomes.
When it comes to testing, GET and POST methods require different testing approaches. For example, testing a GET API may involve verifying that the response data is returned correctly and in the expected format, while testing a POST API may involve verifying that the data is submitted correctly and that it is processed correctly on the server.
Overall, GET and POST are different methods with different purposes and behaviors, and understanding these differences is important for properly testing web APIs that use these methods.
- POST vs PUT vs PATCH – example for each
POST, PUT, and PATCH are three commonly used HTTP methods in web APIs that have different purposes and behaviors. Here are examples of each:
- POST: POST is used to submit data to be processed by a web server. For example, a POST API could be used to create a new user in a database. Here’s an example of a POST request to create a new user:
POST /users HTTP/1.1 Host: example.com Content-Type: application/json { “name”: “John Doe”, “email”: “john.doe@example.com”, “password”: “password123” }
- PUT: PUT is used to replace an existing resource on the web server. For example, a PUT API could be used to update an existing user’s information. Here’s an example of a PUT request to update a user’s information:
PUT /users/123 HTTP/1.1 Host: example.com Content-Type: application/json { “name”: “Jane Doe”, “email”: “jane.doe@example.com”, “password”: “newpassword456” }
- PATCH: PATCH is used to modify an existing resource on the web server. Unlike PUT, which replaces the entire resource, PATCH allows you to modify specific parts of the resource. For example, a PATCH API could be used to update an existing user’s email address. Here’s an example of a PATCH request to update a user’s email address:
PATCH /users/123 HTTP/1.1 Host: example.com Content-Type: application/json { “email”: “newemail@example.com” }
In each of these examples, the request method used (POST, PUT, or PATCH) corresponds to the specific action being performed on the resource (create, replace, or modify), and the request body contains the data to be processed by the server.
- What do you mean when you say PUT is idempotent? Conditions for idempotency?
When we say that a HTTP method like PUT is idempotent, it means that multiple identical requests will have the same effect as a single request. In other words, sending the same PUT request multiple times will not result in different outcomes. This is because the server will process the request the same way every time, resulting in the same state of the resource on the server.
To be idempotent, a HTTP method must meet the following conditions:
- The request should have the same effect whether it is sent once or multiple times.
- The request should not have any side effects on the server or other resources, apart from modifying the resource that the request is intended for.
- The response to the request should be the same, regardless of the number of times the request is sent.
- The request should not depend on any external factors or variables that may change between requests.
In the case of PUT, the idempotency property comes from the fact that sending the same request multiple times will always result in the same resource state on the server. For example, if a PUT request is used to update a user’s information, sending the same request twice will result in the same user information being stored on the server. This can be useful for ensuring data consistency and avoiding unintended side effects.
- Do you follow any strategy for sending large payloads in POST.
Yes, when dealing with large payloads in POST requests, it’s important to follow a strategy to ensure the request is sent and received successfully without any issues. Here are some strategies to consider:
- Use compression: Compressing the payload before sending it can help reduce the size of the request and improve performance. Popular compression algorithms include Gzip and Deflate.
- Use chunked encoding: Chunked encoding allows the payload to be sent in smaller pieces instead of one large block, which can help reduce the likelihood of timeout errors or other issues that can occur when sending large requests.
- Use pagination: If the data being sent in the payload is large and can be logically divided into smaller chunks, consider using pagination to split it into smaller requests. This can help improve performance and reduce the likelihood of timeout errors.
- Optimize the payload: Review the payload to see if there are any unnecessary or redundant data that can be removed. This can help reduce the size of the request and improve performance.
- Use a dedicated file transfer service: If the payload includes large files, consider using a dedicated file transfer service like AWS S3, Google Cloud Storage or Dropbox to transfer the files separately from the API request. The API request can then reference the file location instead of including the file directly in the payload.
Overall, the strategy used will depend on the specific requirements and limitations of the API and the payload being sent. It’s important to test the approach thoroughly to ensure the request is sent and received successfully and without any errors.
- Is it a good idea to have assertions for request headers when testing APIs ?
Yes, it is a good idea to have assertions for request headers when testing APIs. Request headers can provide important information about the client making the request, the format of the request data, and other metadata that can affect how the server processes the request.
Some examples of request headers that may be important to test include:
- Content-Type: This header specifies the format of the request data, such as JSON, XML, or form data. It’s important to test that the correct Content-Type header is being sent and received to ensure the server can process the request data correctly.
- Authorization: This header contains authentication information for the client making the request, such as a token or API key. Testing that the correct Authorization header is being sent and received can help ensure that only authorized clients can access protected resources.
- Accept: This header specifies the format of the response data that the client expects, such as JSON or XML. Testing that the correct Accept header is being sent and received can help ensure that the server returns the response data in the expected format.
By including assertions for request headers in your API tests, you can help ensure that the API is behaving as expected and that the client and server are communicating correctly.
- How do you get a request header in Rest-Assured?
In Rest-Assured, you can get a request header by using the header(String name) method, which retrieves the value of the specified header. Here’s an example of how to use this method:
vbnet
Response response = given() .header(“Authorization”, “Bearer token123”) .header(“Content-Type”, “application/json”) .when() .get(“/api/users”); String contentType = response.getHeader(“Content-Type”);
In this example, the given() method sets two request headers, “Authorization” and “Content-Type”, and the when() method sends a GET request to the “/api/users” endpoint. The getResponseHeader(String name) method is then used to retrieve the value of the “Content-Type” header from the response.
Note that if the specified header is not present in the response, the getResponseHeader(String name) method will return null.
- If I send a text file as an input in a POST call, what will be the content-type?
If you are sending a text file as input in a POST call, the Content-Type header should be set to text/plain. This indicates that the content being sent in the request body is plain text.
However, if the text file contains data in a specific format, such as JSON or XML, you may want to set the Content-Type header to the appropriate media type for that format. For example, if the text file contains JSON data, the Content-Type header should be set to application/json. If the text file contains XML data, the Content-Type header should be set to application/xml.
It’s important to ensure that the Content-Type header is set correctly, as this can affect how the server processes the request and the format of the response data that is returned.
- Key things to test when you API response feeds into a down stream system?
When an API response feeds into a downstream system, there are several key things that should be tested to ensure the system is functioning correctly. Here are some examples:
- Data Integrity: The data being passed to the downstream system should be checked for completeness, accuracy, and consistency. This includes ensuring that all required data is present, data types are correct, and data values are within acceptable ranges.
- Data Mapping: If the data format between the API and downstream system is different, it is important to test that the data is mapped correctly to the expected format. This includes testing that the data is properly transformed and that any required fields are included in the mapped data.
- Data Volume: The volume of data being passed to the downstream system should be tested to ensure that it can handle the expected load. This includes testing the system with both small and large data volumes to ensure that performance is consistent.
- Error Handling: Error handling should be tested to ensure that any errors in the downstream system are properly reported back to the API. This includes testing for error messages, error codes, and any other relevant information that will help with debugging and troubleshooting.
- System Integration: The API should be tested in the context of the entire system to ensure that all components are integrated correctly. This includes testing the API with other systems that it may interact with, such as databases, messaging systems, and other APIs.
By testing these key areas, you can help ensure that the API is functioning correctly and that the downstream system is able to process the data as expected.
- URI vs URL – with a simple example.
URI (Uniform Resource Identifier) and URL (Uniform Resource Locator) are often used interchangeably, but they actually have slightly different meanings.
A URI is a string of characters that identifies a name or a resource on the Internet. It can be used to identify a resource by name, by location, or by both. A URI consists of a scheme (such as “http” or “ftp”), followed by a colon, two slashes, and a resource identifier.
A URL is a specific type of URI that identifies the location of a resource on the Internet. It includes the scheme, hostname, port number (if necessary), and the path to the resource. For example, https://www.example.com/index.html is a URL that identifies the location of a web page on the example.com domain.
Here’s a simple example to illustrate the difference between URI and URL:
URI: mailto:example@example.com
This URI identifies the email address “example@example.com”. It uses the “mailto” scheme to indicate that the resource is an email address.
URL: https://www.example.com/index.html
This URL identifies the location of a web page on the example.com domain. It uses the “https” scheme to indicate that the resource should be accessed securely over HTTPS, the “www.example.com” hostname to indicate the server hosting the resource, and the “/index.html” path to indicate the specific resource being requested.
- 13. ﹖
The JSON Web Token (JWT) format is commonly used for authentication in APIs. JWT is a compact, URL-safe means of representing claims to be transferred between two parties. It consists of three parts separated by dots: a header, a payload, and a signature. Here’s how it works in an API context:
- The client sends a request to the API with an authorization header containing a JWT token.
- The API validates the JWT token by verifying the signature, decoding the payload, and checking the expiration time.
- If the JWT token is valid, the API grants access to the requested resource.
- If the JWT token is not valid, the API returns an error response to the client.
The JWT format works well for authentication in APIs because it is self-contained, meaning that all the information needed to validate the token is contained within the token itself. This makes it easy to transmit and use in distributed systems, and reduces the need for server-side storage and lookup of authentication information. Additionally, because JWT tokens are signed, they are tamper-evident, meaning that any modification to the token will invalidate the signature and cause the token to be rejected.
- Do you know if caching is applied in the rest api’s that you test? How do you test caching in api’s
Caching is a common technique used in REST APIs to improve performance by reducing the number of requests that need to be made to the server. Depending on the implementation, caching may be applied at various levels such as the client-side (e.g., browser caching), server-side (e.g., reverse proxy caching), or the API itself.
To test caching in APIs, you can follow these steps:
- Check if caching is enabled: You can check if caching is enabled by inspecting the response headers. If caching is enabled, you should see headers such as “Cache-Control”, “Expires”, or “ETag”.
- Verify caching behavior: To verify that caching is working as expected, you can make a request to the API, and then make the same request again after a certain period of time has elapsed. If caching is working correctly, you should see a cached response, which should be served much faster than the original request.
- Test cache invalidation: You can test cache invalidation by making a request to the API, modifying the resource (e.g., updating a record), and then making the same request again. If the cache is working correctly, the updated resource should be returned instead of the cached response.
- Test cache control headers: You can also test the behavior of various cache control headers by modifying them and observing the effect on caching behavior. For example, you can modify the “max-age” value in the “Cache-Control” header to control how long responses are cached.
Overall, testing caching in APIs requires careful attention to response headers, request and response timing, and cache control headers. It’s important to ensure that caching behavior is consistent with the expected behavior, and that cache invalidation is working correctly.
- How do you test expired or invalid tokens in your API’s?
Testing expired or invalid tokens in APIs is an important part of ensuring the security and functionality of your API. Here are some steps you can take to test expired or invalid tokens in your API:
- Obtain an expired or invalid token: To test expired or invalid tokens, you first need to obtain one. You can do this by intentionally creating a token with an expiration date in the past, or by modifying a valid token to make it invalid.
- Make an API request with the expired or invalid token: Next, you can attempt to make an API request using the expired or invalid token. Depending on the implementation of your API, this may result in an error response or a response indicating that the token is invalid or has expired.
- Verify the response: After making the request with the expired or invalid token, you should examine the response to ensure that it is consistent with your expectations. For example, you may expect to see an error message indicating that the token is invalid or has expired.
- Test token refresh or renewal: In some cases, you may want to test the behavior of token refresh or renewal. To do this, you can attempt to make an API request using a valid token that is about to expire, and then observe the behavior of the API in response to the expired token. Depending on the implementation of your API, this may trigger a token refresh or renewal, allowing you to continue making requests without interruption.
Overall, testing expired or invalid tokens in APIs requires careful attention to token expiration dates, error responses, and token refresh or renewal mechanisms. By testing these scenarios thoroughly, you can ensure that your API is secure and functional under a range of conditions.
- 16. test , tell us some of the best practices that you follow for testing such user permissions in API’s.
Testing user roles and permissions in APIs is critical to ensure that sensitive data and functionality are protected from unauthorized access. Here are some best practices that I follow for testing user roles and permissions in APIs:
- Identify the different user roles and permissions: Before testing user roles and permissions in APIs, it’s important to understand the different roles and permissions that exist within your application. This may include roles such as “admin”, “user”, or “guest”, and permissions such as “read”, “write”, or “delete”.
- Use role-based testing: Role-based testing involves testing each user role separately to ensure that they have the appropriate access to resources and functionality within the API. This can be done by creating test cases for each role and verifying that the API behaves as expected.
- Test permissions for each resource: For each resource that is accessible through the API, you should test that the appropriate permissions are required to access or modify it. This can be done by creating test cases that attempt to access or modify resources with different levels of permissions, and verifying that the API behaves as expected.
- Use mock data: When testing user roles and permissions, it’s important to use mock data to simulate different scenarios and ensure that the API behaves as expected in each case. This can include creating mock users with different roles and permissions, and using them to test different parts of the API.
- Test edge cases: In addition to testing the main user roles and permissions, it’s important to test edge cases such as invalid or unexpected inputs, and scenarios where a user’s role or permissions change dynamically. This can help uncover potential security vulnerabilities or other issues that may arise in real-world usage of the API.
Overall, testing user roles and permissions in APIs requires careful attention to detail and a thorough understanding of the different roles and permissions that exist within your application. By following these best practices, you can ensure that your API is secure and functional for users with different levels of access.
- Have you heard of the term rate-limiting? Can you explain when should we use rate limiting in API’s
Yes, I have heard of the term rate-limiting in the context of APIs. Rate limiting is a technique used to control the rate at which clients can make requests to an API. It involves setting a limit on the number of requests that can be made within a specified time period, typically measured in seconds or minutes.
Rate limiting can be used in APIs to prevent abuse or overuse of the API by clients. For example, if an API allows a maximum of 100 requests per minute, rate limiting can be used to ensure that clients do not exceed this limit. This can help prevent issues such as server overload, data theft, or other security vulnerabilities that may arise from excessive API usage.
Rate limiting can also be used to prioritize certain types of requests over others. For example, an API may prioritize requests from paying customers over free users, or prioritize requests for critical data over non-critical data. By setting different rate limits for different types of requests, an API can ensure that the most important requests are processed first and that resources are allocated appropriately.
Overall, rate limiting can be an effective technique for managing API usage and preventing abuse or overuse. By setting appropriate rate limits and prioritizing requests, APIs can ensure that resources are allocated efficiently and that users are able to access the data and functionality they need without causing harm to the system.
- Do you generate reports of the api tests that you run? What are some key attributes to include in the report.
Yes, generating reports for API tests is an essential step in ensuring the quality and reliability of the API. A well-designed report can provide useful information to stakeholders, including developers, testers, and management, about the status and quality of the API being tested.
Some key attributes to include in an API test report are:
- Summary: The summary should provide a high-level overview of the test results, including the number of tests run, the number of tests passed and failed, and any errors or issues encountered during testing.
- Test cases: The report should include a list of all the test cases that were run, along with their results. This can provide detailed information about the specific areas of the API that were tested and any issues or bugs that were discovered.
- Logs: The report should include detailed logs of each test case run, including any errors or exceptions that were encountered. This can help developers diagnose and troubleshoot issues more easily.
- Metrics: The report should include key metrics such as response time, latency, and throughput, which can provide insight into the performance and reliability of the API.
- Recommendations: The report should include recommendations for any improvements or changes that could be made to the API based on the test results. This can help developers and management prioritize areas for improvement and make informed decisions about future development efforts.
- Attachments: The report can also include attachments such as screenshots, videos, or other documentation that provide additional context or detail about the test results.
Overall, a well-designed API test report can provide valuable insights into the quality and reliability of the API, and help stakeholders make informed decisions about development and testing efforts.
- Have you heard of the term api gateway? What does it do?
An API Gateway is a server that acts as an intermediary between the API client (such as a web or mobile application) and the back-end services that the API exposes. Its main purpose is to manage, secure, and optimize API traffic by performing various functions such as:
- Routing: API Gateway can route incoming API requests to the appropriate back-end service based on the request URL or other parameters.
- Load balancing: API Gateway can distribute API requests across multiple instances of a back-end service to improve performance and reliability.
- Caching: API Gateway can cache API responses to reduce latency and improve API performance.
- Authentication and authorization: API Gateway can handle user authentication and authorization, ensuring that only authorized users can access the API.
- Security: API Gateway can enforce security policies such as SSL/TLS encryption, rate limiting, and firewall rules to protect the API from attacks.
- Monitoring: API Gateway can provide real-time monitoring and analytics on API traffic, usage, and performance.
Overall, an API Gateway serves as a central point of control and management for an API, allowing developers to focus on building and maintaining the back-end services, while the gateway handles the complexities of API traffic management, security, and optimization.
- What is the difference in path param and query params?
Path parameters and query parameters are both ways to pass data to an API endpoint, but they are used for different purposes and have different syntax.
Path parameters are part of the endpoint’s URL, usually indicated by a colon (:) followed by a parameter name. They are used to identify a specific resource or entity within the API. For example, in the URL “/users/:id”, “:id” is a path parameter that represents a specific user’s ID. Path parameters are required and must be included in the URL for the API to function properly.
Query parameters, on the other hand, are optional parameters that come after the endpoint’s URL and are separated by a question mark (?). They are used to filter, sort, or paginate the API response. For example, in the URL “/users?sort=name&limit=10”, “sort” and “limit” are query parameters that sort the user list by name and limit the results to 10 users. Query parameters are not required and can be omitted if the API user wants to retrieve all available data.
In summary, path parameters are used to identify a specific resource or entity, while query parameters are used to modify the API response. Path parameters are part of the endpoint’s URL and are required, while query parameters are optional and come after the endpoint’s URL.
- Do we need to use POJO class and serialisation in RestAssured, when we can directly send request body in the form of String?
it is not necessary to use POJO classes and serialization when sending a request body in RestAssured. You can also send the request body as a string.
However, using POJO classes and serialization can make the code more readable and maintainable, especially when dealing with large and complex request bodies. It can also help catch errors during the compilation phase rather than during the runtime, which can save time and effort in the long run.
Additionally, using POJO classes and serialization can help ensure that the data being sent in the request body is in the correct format and follows the data contract defined by the API. If the data is sent as a string, it may not be easy to detect formatting errors or inconsistencies.
Ultimately, the decision of whether to use POJO classes and serialization or send the request body as a string depends on the specific use case and the preference of the developer or team.
- Can I use cookies with rest assured – if so how can I set a cookie for a domain?
Yes, RestAssured supports working with cookies. You can use the given() method to set a cookie for a specific domain. Here is an example of how to set a cookie for a domain:
given() .cookie(“cookieName”, “cookieValue”) .cookie(“anotherCookieName”, “anotherCookieValue”) .cookie(“cookieName”, “cookieValue”, “domainName”) .when() .get(“https://example.com/api/resource”) .then() .statusCode(200);
In the example above, the given() method sets three cookies: cookieName, anotherCookieName, and cookieName with the domain name domainName. The when() method sends a GET request to the specified endpoint, and the then() method verifies that the response status code is 200.
To set a cookie for a specific domain, you can add the domain name as the third parameter in the cookie() method, as shown in the example.
- Do you know what is a HEAD request? Can you think of a scenario when HEAD request would be needed.
Yes, I do know what a HEAD request is. A HEAD request is a request method supported by HTTP used to request the headers that would be returned if the same request were made with a GET method, but without the response body. In other words, a HEAD request only returns the metadata associated with the resource being requested, such as the status code, headers, and content length, but not the actual content.
A scenario where a HEAD request would be useful is when a client wants to know if a resource exists or not, without actually retrieving the full contents of the resource. For example, a web crawler might use a HEAD request to check if a page has changed since it was last crawled, without actually downloading the page content again. Similarly, a client might use a HEAD request to check the status of a file download without actually downloading the file itself.
- Is POST a cacheable method? Is PUT a cacheable method?
POST is not a cacheable method, according to the HTTP specification. This means that responses to POST requests should not be cached by a client or an intermediary cache. This is because POST requests are typically used to create a new resource or modify an existing resource on the server, and the response may depend on the state of the resource at the time the request was made.
PUT, on the other hand, is a cacheable method, provided that certain conditions are met. According to the HTTP specification, a response to a PUT request is cacheable if and only if the following conditions are met:
- The request message contains an If-Match or If-Unmodified-Since header, indicating that the client has a current representation of the resource being updated.
- The response message includes an ETag or Last-Modified header, indicating the new state of the resource after the update.
If these conditions are met, a client or intermediary cache can cache the response to a PUT request for future use, assuming that the cache obeys the caching rules specified in the HTTP specification.
- Difference between api virtualisation and mocking?
API virtualization involves creating a virtualized version of an API that behaves like the real API but is not actually connected to the backend systems. This is often done to allow testing of APIs in isolation, before the backend systems are fully developed or available. API virtualization can also be used to simulate different scenarios, such as slow responses or error conditions, to test how client applications handle those situations.
On the other hand, API mocking involves creating a fake implementation of an API that mimics the expected behavior of the real API but doesn’t actually execute any code from the real API. This is often used to test the integration of client applications with the API without the need for a fully functional backend system.
In summary, API virtualization is used to simulate the behavior of the actual API, while API mocking is used to simulate the behavior of the API for testing purposes.
- What is JSON Schema? Can I use same json schema for validating the response of two different api’s?
JSON Schema is a vocabulary that allows us to validate the structure and data types of JSON data. It provides a way to define the expected shape of the JSON document, including required properties, data types, and constraints.
Regarding the question of whether the same JSON Schema can be used for validating the response of two different APIs, it depends on the structure of the responses. If the responses have the same structure and data types, then the same JSON Schema can be used to validate both responses. However, if the responses have different structures or data types, then separate JSON Schemas would need to be created for each response. It is always a good practice to create separate JSON Schemas for each API response to ensure accurate validation.
- What is API caching and in how many ways can we cache api response.
API caching is the process of storing API responses in a cache to avoid making the same API request repeatedly, thus improving the performance of the API and reducing server load. When an API response is cached, subsequent requests for the same API endpoint can be served from the cache rather than making a new request to the server.
There are different ways to cache API responses:
- Client-side caching: In client-side caching, the API response is cached by the client (e.g. browser) for a specific period. The cached response can be used for subsequent requests until it expires.
- Server-side caching: In server-side caching, the API response is cached by the server. When a subsequent request is received for the same API endpoint, the cached response is served from the cache rather than generating a new response from the server.
- Content delivery network (CDN) caching: CDN caching is a type of server-side caching where the API response is cached by a CDN node. This improves the performance of the API by serving the response from the nearest CDN node to the client.
- Database caching: In database caching, the API response is cached in a database. Subsequent requests for the same API endpoint can be served from the cache rather than making a new request to the server.
- Gateway caching: Gateway caching is a type of server-side caching where the API response is cached by the API gateway. When a subsequent request is received for the same API endpoint, the cached response is served from the cache rather than generating a new response from the server.
It’s important to note that caching can introduce some challenges, such as dealing with stale data and cache invalidation. Therefore, careful consideration should be given when implementing caching strategies for APIs.
========================================================================================