Question: What is API
Answer: API stands for Application Programming Interface. It is a set of rules and protocols that allows different software applications to communicate with each other. APIs define the methods and data formats that developers can use to request and exchange information between applications, services, or systems.Question: API Examples
Answer:
API Call Action
GET /users List all users
GET /users?name={username} Get user by username
GET /users/{id} - Get user by ID
GET /users/{id}/configurations Get all configurations for user
POST /users/{id}/configurations Create - a new configuration for user
DELETE /users/{id}/configurations/{id} Delete configuration for user
PATCH /users/{id}/configuration/{id} Update configuration for use
Question: Explain API Gateway
Answer: An API Gateway is a server or service that acts as an intermediary between an application or client and a collection of microservices or backend services.
It serves as a central entry point for managing and routing requests to various backend services, while also providing a range of capabilities to enhance the security, performance, and functionality of APIs.
Question: Web Services
Answer: Web services are a standardized way for software applications to communicate and exchange data over the internet or other network protocols. They provide a set of rules and protocols that enable different systems, written in different programming languages and running on different platforms, to interact with each other seamlessly. Web services allow for the integration of disparate systems and enable them to work together to achieve specific tasks or share data.
Types of Web Services:
SOAP Web Services: These follow the SOAP protocol and are known for their strict standards and features like built-in security and reliability. They use XML for message formatting.
RESTful Web Services: REST (Representational State Transfer) is an architectural style for designing networked applications. RESTful web services use HTTP methods (GET, POST, PUT, DELETE) to perform CRUD (Create, Read, Update, Delete) operations on resources, making them simple and lightweight.
JSON-RPC and XML-RPC: These are remote procedure call (RPC) protocols that allow clients to invoke methods or functions on a remote server using JSON or XML as the message format.
GraphQL: GraphQL is a query language for APIs that allows clients to request exactly the data they need, minimizing over-fetching and under-fetching of data.
Question: Differences between SOAP and REST API
Answer: 1.SOAP stands as Simple Object Access Protocol. REST stands as Representational State Transfer.
2.SOAP is a protocol. REST is an architectural pattern.
3.SOAP can work with XML format. In SOAP all the data passed in XML format. REST permit different data format such as Plain text, HTML, XML, JSON etc. But the most preferred format for transferring data is in JSON.
Question: How do you handle error handling and exception testing in API testing?
Answer: Handling error handling and exception testing in API testing is crucial to ensure that an API behaves correctly when errors or exceptional conditions occur. This testing helps verify that the API returns appropriate error responses and handles exceptional situations gracefully. Here's how you can handle error handling and exception testing in API testing:
1. Identify Error Scenarios:
- Begin by identifying the potential error scenarios specific to the API you are testing. Common error scenarios include invalid input data, authentication failures, server errors, and resource not found errors.
2. Create Test Cases for Error Scenarios:
- Develop test cases that intentionally trigger these error scenarios. For example:
- Sending invalid or missing parameters.
- Using incorrect authentication credentials.
- Simulating server-side errors or timeouts.
- Requesting non-existent resources.
3. Expected Error Responses:
- Determine the expected error responses for each error scenario. This includes the HTTP status code, response body content, and headers. Refer to the API's documentation to understand the expected error format.
4. Automation:
- Implement automation scripts to execute these test cases systematically. Automation helps ensure that error scenarios are consistently tested and that the expected error responses are verified.
5. Assertions:
- In your test automation framework, define assertions to check whether the received error response matches the expected response. Assertions should include:
- Verifying the correct HTTP status code (e.g., 400 for bad request, 401 for unauthorized).
- Validating the error message and error code in the response body.
- Checking response headers, if relevant.
6. Edge Cases:
- Consider testing edge cases to ensure that the API handles extreme or boundary conditions correctly. For example, if an API accepts numeric values, test the minimum and maximum allowed values.
7. Negative Testing:
- Negative testing involves testing scenarios where unexpected or invalid data is provided to the API. For example, sending a string to an API that expects a number. Ensure that the API responds appropriately and provides informative error messages.
8. Rate Limiting and Throttling:
- If the API has rate limiting or throttling mechanisms, create tests to verify that these mechanisms are enforced correctly. Test scenarios where the rate limit is exceeded and ensure that the API responds with the appropriate rate-limiting error.
9. Testing Error Recovery:
- For scenarios involving temporary errors, such as network issues or server timeouts, test the API's ability to recover gracefully. Retry requests after temporary errors to confirm that the API eventually succeeds when the issue is resolved.
10. Logging and Monitoring:
- Set up logging and monitoring to capture error responses and exceptions during testing. This helps identify issues that may not be immediately visible during test execution.
11. Documentation and Reporting:
- Document the error scenarios, expected responses, and test results. Create clear and concise reports, including details of any failures or deviations from the expected behavior.
12. Regression Testing:
- Include error and exception test cases in your regression testing suite to ensure that error handling remains effective as the API evolves over time.
By systematically testing error handling and exception scenarios in your API, you can ensure that the API behaves reliably and provides meaningful error information to users and clients. This helps improve the overall quality and resilience of the API.
Question: How do you handle authentication in API testing?
Answer: Handling authentication in API testing is essential to ensure that only authorized users or applications can access the API's resources and functionality. Authentication mechanisms vary depending on the API and its security requirements. Here are some common methods for handling authentication in API testing:
1. API Key Authentication:
How it works: The client includes an API key in the request header, query parameter, or request body. The server validates the API key to grant or deny access.
When to use: API key authentication is simple and suitable for public APIs or when you want to track usage.
2. Token-based Authentication (e.g., OAuth2):
How it works: Clients obtain access tokens by authenticating with the authorization server. They then include these tokens in API requests. The server validates the token to grant or deny access.
When to use: Token-based authentication is commonly used for securing APIs that require user authentication, access control, and permissions management.
3. Username and Password Authentication:
How it works: Clients include a username and password in the request header or request body. The server validates the credentials.
When to use: This method is used for authenticating users with their credentials. It's commonly used in API testing for services that provide user-specific data or actions.
4. Bearer Token Authentication:
How it works: Clients include a bearer token in the request header's `Authorization` field, typically in the format "Bearer token_value."
When to use: Bearer token authentication is commonly used with OAuth2 or token-based authentication systems.
5. Basic Authentication:
How it works: Clients include a username and password in the request header, encoded in Base64 format. For example, "Authorization: Basic base64(username:password)."
When to use: Basic authentication is a simple method often used with HTTP or when a more secure method like OAuth2 is not required.
6. API Secret and Signature Authentication:
How it works: Clients send a request with an API key and a unique signature generated based on the request parameters and a secret key. The server verifies the signature.
When to use: This method is suitable for securing sensitive operations and is common in payment gateway APIs.
When conducting API testing with authentication, here are some best practices to consider:
Test with Valid Credentials: Start by testing with valid credentials to ensure that the authentication process works correctly.
Test with Invalid Credentials: Test scenarios where authentication fails, such as incorrect passwords, expired tokens, or missing API keys, to ensure proper error handling.
Test with Different Authentication States: Test with different authentication states, such as authenticated, unauthenticated, and partially authenticated, to verify that access is granted or denied as expected.
Use Test Data: Create test accounts or users specifically for testing purposes to avoid affecting production data.
Parameterization: Parameterize authentication credentials and tokens, so you can easily switch between different test scenarios and environments.
Secure Storage: Ensure that sensitive authentication credentials and tokens are securely stored and managed, especially in automated test scripts.
Token Refresh: If using token-based authentication, include tests for token refresh mechanisms to ensure uninterrupted access during longer test scenarios.
By following these best practices and using the appropriate authentication method, you can effectively test the security and functionality of APIs in various scenarios while safeguarding sensitive data and ensuring proper access control.
Question: Can you describe the typical components of an API request and response?
Answer: API requests and responses consist of various components that facilitate the communication between a client (the entity making the request) and a server (the entity processing the request). These components help define the structure and behavior of the interaction. Here are the typical components of an API request and response:
API Request Components
1. HTTP Method (or Verb): This specifies the type of action to be performed on the resource. Common HTTP methods include GET (retrieve data), POST (create a new resource), PUT (update a resource), DELETE (remove a resource), and more.
2. Endpoint (URL): The endpoint is the specific URL or URI (Uniform Resource Identifier) that the client sends the request to. It identifies the resource or service being accessed.
3. Headers: Request headers contain additional information about the request, such as the content type, authentication credentials, caching directives, and more. Some common headers include:
- Content-Type: Describes the format of the request body (e.g., JSON, XML).
- Authorization: Contains authentication tokens or credentials.
- Accept: Specifies the desired response format.
- User-Agent: Provides information about the client making the request.
4. Parameters (Query or Path Parameters): Parameters are used to send additional data to the server, often to filter, sort, or customize the response. Query parameters are included in the URL (e.g., `?param=value`), while path parameters are part of the URL's path (e.g., `/resource/{id}`).
5. Request Body (Payload): The request body contains the data that the client sends to the server, typically in JSON, XML, or other formats. It is used for operations like creating or updating resources.
6. Authentication: In some cases, API requests require authentication, which may involve API keys, tokens, or username/password combinations, depending on the authentication method used.
API Response Components:
1.HTTP Status Code: The status code is a three-digit number that indicates the outcome of the request. Common status codes include:
- 200 (OK): Successful request with a response.
- 201 (Created): The request resulted in the creation of a new resource.
- 204 (No Content): The request was successful, but there is no response body.
- 400 (Bad Request): The request was malformed or had invalid parameters.
- 401 (Unauthorized): Authentication is required or failed.
- 404 (Not Found): The requested resource does not exist.
- 500 (Internal Server Error): An error occurred on the server.
2. Headers: Response headers convey metadata about the response, such as the content type, server information, and caching directives.
3. Response Body: The response body contains the data returned by the server. It is often in JSON, XML, or other formats, depending on the API's design.
4. Error Messages: In case of errors or exceptions, the response body may include error messages or details explaining what went wrong. These messages can help developers diagnose and handle issues.
5. Pagination Information: For APIs that return large sets of data, pagination information may be included in the response to indicate how to retrieve additional results (e.g., page number, page size).
Question: HTTP Request Methods
Answer: GET
It fetches the information from the server. Moreover, it is the most commonly used method which does not have a request body. Every time you open a website, the Get request fires to retrieve the website contents. Additionally, it is equivalent to the
POST
It works to send data to the server. User may add or update data using the Post request. They send the information that needs to update in the request body.
PUT
It is similar to the Post method since it updates the data. The only difference is that we use it when we have to replace an existing entity completely
PATCH
It s again similar to Post and Put methods, but user use it when they have to update some data partially. Moreover, unlike the Post and Put methods, user may send only the entity that needs updation in the request body with the Patch method.
HEAD
It is similar to the Get method, but it retrieves only the header data and not the entire response body. User use it when they need to check the document's file size without downloading the document.
DELETE
It deletes the server's representations of resources through the specific URL. Additionally, just like the Get method, it does not have a request body.
OPTIONS
It is not a widely used method when compared to other ones. It returns data specifying the different methods and the operations supported by the server at the
Question: What is Latency in API testing?
Question: HTTP Response Status Codes
Answer: 1xx
informational response, request was received, continuing process
100
Continue: The client can continue with the request as long as it doesn't get rejected.
101
Switching Protocols: The server is switching protocols.
102
Processing, It indicates that the server has received and is processing the request, but no response is available yet.
103
Early Hints, it primarily intended to be used with the Link header, letting the user agent start preloading resources while the server prepares a response.
2xx
Success, request was successfully received, understood, and accepted
200
OK: The request succeeded
201
Created: The request succeeded, and a new resource was created as a result. This is typically the response sent after POST requests, or some PUT requests.
202
Accepted: Request accepted for processing, but in progress
203
Non-Authoritative Information: The information in the entity header is not from an original source but a third-party
204
No Content: Response with status code and header but no response body
205
Reset Content: The form for the transaction should clear for additional input
206
Partial Content: Response with partial data as specified in Range header
207
Multi-Status, Conveys information about multiple resources, for situations where multiple status codes might be appropriate.
3xx
Redirection, further action needed in order to complete the request
300
Multiple Choices: Response with a list for the user to select and go to a location
301
Moved Permanently: Requested page moved to a new url
302
Found: Requested page moved to a temporary new URL
303
See Other: One can find the Requested page under a different URL
305
Use Proxy: Requested URL need to access through the proxy mentioned in the Location header
307
Temporary Redirect: Requested page moved to a temporary new URL
308
Permanent Redirect: This means that the resource is now permanently located at another URI, specified by the Location: HTTP Response header.
4xx
Client Error, request contains bad syntax or cannot be fulfilled
400
Bad Request: Server unable to understand the request
401
Unauthorized: Requested content needs authentication credentials
403
Forbidden: Access is forbidden
404
Not Found: Server is unable to find the requested page
405
Method Not Allowed: Method in the request is not allowed
407
Proxy Authentication Required: Need to authenticate with a proxy server
408
Request Timeout: The request took a long time as expected by the server
409
Conflict: Error in completing request due to a conflict
411
Length Required: We require the "Content-Length" for the request to process
415
Unsupported Media Type: Unsupported media-type
417
Expectation Failed, it means the expectation indicated by the Expect request header field cannot be met by the server.
421
Misdirected Request, request was directed at a server that is not able to produce a response.
423
Locked, the resource that is being accessed is locked
429
Too Many Requests,user has sent too many requests in a given amount of time
5xx
Server Error, the server failed to fulfil an apparently valid request
500
Internal Server Error: Request not completed due to server error
501
Not Implemented: Server doesn't support the functionality
502
Bad Gateway: Invalid response from an upstream server to the server. Hence, the request not complete
503
Service Unavailable: The server is temporarily down
504
Gateway Timeout: The gateway has timed out
505
HTTP Version Not Supported: Unsupported HTTP protocol version
507
Insufficient Storage, method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the
511
Network Authentication Required, it indicates that the client needs to authenticate to gain network access
Question: Explain restassured api testing in java
Answer: RestAssured is a Java library that provides a domain-specific language (DSL) for testing RESTful APIs. It simplifies the process of writing and validating API tests by offering a fluent and expressive syntax. RestAssured allows you to perform various HTTP operations like GET, POST, PUT, DELETE, etc., and validate the response against expected values using assertions.
Dependency -
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.3.2</version>
<scope>test</scope>
</dependency>
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
import org.testng.annotations.Test;
public class APITest {
@Test
public void testGETRequest() {
given()
.baseUri("https://jsonplaceholder.typicode.com")
.basePath("/posts/1")
.when()
.get()
.then()
//.log().body();
.statusCode(200)
.body("userId", equalTo(1))
.body("id", equalTo(1));
}
}
Question: Various methods in restassured api testing in java
Answer:
1. Setting Up Base URI and Base Path:
`baseURI(String uri)`: Sets the base URI for all requests.
`basePath(String path)`: Sets the base path for all requests.
2. Request Specification:
`given()`: Starts building the request specification.
`given().config(RestAssured.config())`: Configures the request specification using a given RestAssured configuration.
`given().auth().basic(username, password)`: Specifies basic authentication credentials.
`given().contentType(ContentType.JSON)`: Sets the content type of the request.
`given().header(String name, String value)`: Adds a header to the request.
`given().body(Object object)`: Sets the request body.
3. HTTP Methods:
`get(String path)`: Performs a GET request.
`post(String path)`: Performs a POST request.
`put(String path)`: Performs a PUT request.
`delete(String path)`: Performs a DELETE request.
`patch(String path)`: Performs a PATCH request.
4. Response Specification:
`then()`: Starts building the response specification.
`then().statusCode(int statusCode)`: Validates the status code of the response.
`then().contentType(ContentType contentType)`: Validates the content type of the response.
`then().body(String path, Matcher<?> matcher)`: Validates the response body using a Hamcrest matcher.
`then().extract().path(String path)`: Extracts a value from the response body using a JSON path expression.
5. Assertions:
`assertThat()`: Performs assertions on the response using Hamcrest matchers.
6. Logging:
`log().all()`: Logs all request and response details.
`log().ifValidationFails()`: Logs request and response details only if validation fails.
`log().ifError()`: Logs request and response details only if an error occurs.
7. Extracting Response Data:
`extract()`: Extracts data from the response.
`extract().response()`: Extracts the entire response.
`extract().path(String path)`: Extracts a value from the response body using a JSON path expression.
`extract().jsonPath()`: Creates a JsonPath object for parsing JSON response body.
8. Query Parameters and Path Parameters:
`queryParam(String name, Object... values)`: Adds query parameters to the request.
`pathParam(String name, Object value)`: Adds path parameters to the request.
9. Cookies:
`cookie(String name, String value)`: Adds a cookie to the request.
`cookies(Map<String, ?> cookies)`: Adds multiple cookies to the request.
10. Filters:
`filter(Filter filter)`: Adds a filter to the request.
11. Error Handling:
`when().error()` : Handles HTTP error responses.
`exception(Exception.class)`: Specifies exceptions to be thrown during request specification building.
Question: How do you log request and response details in RestAssured?
Answer: You can log request and response details in RestAssured using methods like log().all(), log().ifValidationFails(), and log().ifError().
Question: What is RestAssured?
Answer: RestAssured is a Java library that provides a domain-specific language (DSL) for writing powerful, maintainable tests for RESTful APIs. It simplifies the process of testing RESTful web services and supports various HTTP methods like GET, POST, PUT, DELETE, etc.
public static void main(String[] args) {
// Define base URI
String baseURI = "https://api.example.com";
// Perform GET request
RestAssured.
given()
.get(baseURI+"/fact")
.then()
.statusCode(200)
.log().all(); // Log response
}
}
given()
.get(baseURI+"/fact")
.then()
.statusCode(200) // Validates if the response status code is 200
public void testApi() {
RestAssured.
given()
.get(baseURI)
.then() .log().all()
.assertThat().statusCode(200)
.body("gender", Matchers.equalTo("Value"));
// Validates if the response body contains a specific key-value pair
@Test
public void authApi() {
baseURI = "https://api.example.com";
RestAssured.
given()
.auth().basic("username", "password")
.get("/resource")
.then()
.statusCode(200);
}
@Test
public void authApi() {
baseURI = "https://api.example.com";
RestAssured
.given()
.formParams("param1", "value1", "param2", "value2")
.post("/resource")
.then()
.statusCode(200);
}
public void testApi() {
baseURI = "https://api.example.com";
RestAssured
.given()
.get("/resource")
.then()
.header("Content-Type", "application/json") // Validates the Content-Type header
.header("Server", "Apache"); // Validates the Server header
}
}
@Test
public void testApi() {
String baseURi = "https://api.example.com";
String response = RestAssured.given()
.get(baseURi+"/resource")
.then()
.extract().response().asString();
String value = JsonPath.from(response).getString("key");
System.out.println("Value of key: " + value);
}
@Test
public void testApi() {
String baseURI = "https://api.example.com";
RestAssured.given()
.get(baseURI+"/nonexistent-resource")
.then().log().all()
.statusCode(404)
.statusLine("HTTP/1.1 404 Not Found")
.body("message", Matchers.equalTo("Not Found"));
}
@Test
public void testApi() {
String baseURI = "https://api.example.com";
// Extracting value from response
String userId = RestAssured.given()
.get(baseURI+"/users")
.then()
.extract().path("id[0]");
// Using extracted value in subsequent request
RestAssured.given()
.pathParam("userId", userId)
.get("/users/{userId}/profile")
.then()
.statusCode(200);
}
@Test
public void testApi() {
String baseURI = "https://api.example.com";
RestAssured.given()
.multiPart(new File("path/to/file.txt"))
.post(baseURI+"/upload")
.then()
.statusCode(200);
}
@Test
public void testApi() {
String baseURI = "https://api.example.com";
RestAssured. given()
.cookie("sessionId", "123456789")
.get(baseURI+"/resource")
.then()
.statusCode(200)
.cookie("sessionExpires", "2024-02-14");
}
@Test
public void testApi() {
String baseURI = "https://api.example.com";
RestAssured.given()
.config(RestAssured.config()
.httpClient(HttpClientConfig.httpClientConfig()
.setParam("http.connection.timeout", 5000)
.setParam("http.socket.timeout", 5000)))
.get("/resource")
.then()
.statusCode(200);
}
@Test
public void testApi() {
String baseURI = "https://api.example.com";
RestAssured. given()
.relaxedHTTPSValidation()
.get("/resource")
.then()
.statusCode(200);
}
@Test
public void testApi() {
String baseURI = "https://api.example.com";
RestAssured.given()
.body("{ invalid: json }")
.post("/resource")
.then()
.statusCode(400);
// Assuming 400 Bad Request is expected for invalid input
}
Comments
Post a Comment