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}/configurations/{id} | Update configuration for user |
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. SOAP messages 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 such as GET, POST, PUT, and 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 for Simple Object Access Protocol. REST stands for Representational State Transfer.
2. SOAP is a protocol. REST is an architectural style.
3. SOAP messages use XML for their message format. REST permits different data formats such as plain text, HTML, XML, and JSON. JSON is the most commonly preferred format for transferring data in many REST APIs. Question: How do you handle error handling and exception testing in API testing?
Answer: Handling error 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.
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, such as 400 for Bad Request or 401 for Unauthorized.
- Validating the error message and error code in the response body.
- Checking response headers, if relevant.
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., OAuth 2.0):
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 OAuth 2.0 or other 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 OAuth 2.0 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.
Best Practices for Authentication Testing:
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 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 or submit data), PUT (replace 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.
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, such as page number or page size. Question: HTTP Request Methods
Answer: GET
GET retrieves a representation of a resource from the server. It is commonly used to retrieve data and does not typically contain a request body. For example, when a browser requests a web page, it commonly sends a GET request to retrieve the page contents.
POST
POST is used to submit data to the server for processing. It is commonly used to create resources or trigger operations, and the data is typically included in the request body.
PUT
PUT is used to replace the current representation of a resource with the representation provided in the request. It is commonly used when the client wants to replace an existing entity completely.
PATCH
PATCH is used to apply partial modifications to a resource. The request body generally contains the changes or information needed to modify the resource rather than a complete replacement representation.
HEAD
HEAD is similar to GET, but the server returns the response headers without the response body. It can be used to check metadata such as a resource's size or modification information without downloading the response body.
DELETE
DELETE requests that the server remove the specified resource. A DELETE request commonly does not contain a request body, although HTTP does not universally prohibit a body on DELETE requests.
OPTIONS
OPTIONS requests information about the communication options available for a target resource. It can be used to determine which HTTP methods and other options are supported by the server. It is also commonly involved in CORS preflight requests.
Question: What is Latency in API testing?
Answer: Latency refers to the delay involved in processing an API request and receiving a response. It can include network communication and server processing time. Lower latency generally results in better application responsiveness and performance. Question: Key components of ReadyAPI and how they contribute to API testing
Answer: ReadyAPI is a comprehensive API testing tool that offers various components to facilitate API testing and ensure the quality of web services. The key components of ReadyAPI and their contributions to API testing are as follows:
1. Projects: A project in ReadyAPI serves as a container for artifacts related to API testing. It allows you to organize test cases, test suites, and other resources in a structured manner. Projects help maintain a logical separation of different APIs or services being tested, making it easier to manage and execute tests.
2. TestCases: Test cases are at the core of API testing in ReadyAPI. They represent individual tests or scenarios that you want to execute. You can create multiple test cases within a project to cover various aspects of API functionality and behavior.
3. Test Suites: Test suites are collections of test cases that can be executed together. They allow you to group related tests and define the order in which they should run. This is useful for creating comprehensive test scenarios that involve multiple API endpoints or interactions.
4. Requests: Requests represent the actual API calls you want to make during testing. ReadyAPI supports both REST and SOAP requests. You can configure request parameters, headers, authentication, and more. Requests are essential for simulating interactions with the API under test.
5. Assertions: Assertions are used to validate response data from API calls. ReadyAPI offers a wide range of assertion types, such as status code assertions, content assertions, and schema assertions. Assertions help ensure that the API behaves as expected and that the data returned meets your criteria.
6. Data Sources: Data sources enable data-driven testing in ReadyAPI. You can connect test cases to various data sources such as Excel, databases, or CSV files. This allows you to execute the same test case with different input data, making your testing more thorough and efficient.
7. Environments: Environments in ReadyAPI help manage variables and configurations that might change across different environments, such as development, staging, and production. By switching between environments, you can easily adapt your test cases to various deployment scenarios.
8. Scripting: ReadyAPI provides scripting support using Groovy, which allows you to add custom logic and automation to your test cases. You can use scripts for tasks such as dynamic data generation, complex test case flow control, or custom validations.
9. Reports: ReadyAPI generates detailed reports after test execution. These reports provide insights into test results, including pass/fail status, response data, and logs. Reports are useful for tracking the health of APIs and debugging issues.
10. Integration: ReadyAPI integrates with various tools and platforms, including version control systems, continuous integration/continuous deployment (CI/CD) pipelines, and bug tracking systems. This integration streamlines collaboration and automation in the API testing process.
In summary, ReadyAPI's key components work together to provide a comprehensive and organized approach to API testing. It allows testers to create, manage, execute, and analyze API tests effectively, helping ensure the reliability and quality of web services. Question: HTTP Response Status Codes
Answer: 1xx — Informational
Informational responses indicate that the request was received and the process is continuing.
100 — Continue: The server has received the initial part of the request and indicates that the client may continue sending the request.
101 — Switching Protocols: The server is switching protocols as requested by the client.
102 — Processing: The server has received and is processing the request, but no response is available yet.
103 — Early Hints: The response can be used with the Link header to allow a user agent to preload resources while the server prepares the final response.
2xx — Success
Successful responses indicate that the request was successfully received, understood, and processed or accepted.
200 — OK: The request succeeded.
201 — Created: The request succeeded and a new resource was created as a result. This is commonly returned after POST requests and can also be returned after some PUT requests.
202 — Accepted: The request has been accepted for processing, but processing has not necessarily been completed.
203 — Non-Authoritative Information: The request was successful, but the returned metadata or representation may have been modified or obtained from a transforming proxy rather than directly from the origin server.
204 — No Content: The request succeeded, but there is no response content in the response body.
205 — Reset Content: The request succeeded, and the user agent should reset the document view or input used for the request.
206 — Partial Content: The server is delivering part of the resource, as requested by the Range header.
207 — Multi-Status: The response provides information about multiple resources or operations, with individual status information for each.
3xx — Redirection
Redirection responses indicate that further action may be needed to complete the request.
300 — Multiple Choices: The request has multiple possible representations or responses, from which the user agent may choose.
301 — Moved Permanently: The requested resource has been permanently moved to another URL or URI.
302 — Found: The requested resource is temporarily available at another URL or URI.
303 — See Other: The client should retrieve the requested resource using another URL, typically with a GET request.
305 — Use Proxy: This status code indicates that the requested resource must be accessed through the proxy specified by the response. It is deprecated and should not be used by modern applications.
307 — Temporary Redirect: The requested resource is temporarily available at another URL or URI, and the client should preserve the original request method when following the redirect.
308 — Permanent Redirect: The resource has permanently moved to another URI, and the client should preserve the original request method when following the redirect.
4xx — Client Error
Client error responses indicate that the request contains invalid information or cannot be fulfilled because of a client-side issue.
400 — Bad Request: The server cannot process the request because it is malformed or contains invalid information.
401 — Unauthorized: The request lacks valid authentication credentials or authentication failed.
403 — Forbidden: The server understood the request but refuses to authorize it.
404 — Not Found: The server cannot find the requested resource.
405 — Method Not Allowed: The HTTP method used in the request is not allowed for the requested resource.
407 — Proxy Authentication Required: The client must authenticate with the proxy before the request can be completed.
408 — Request Timeout: The server did not receive a complete request within the time it was prepared to wait.
409 — Conflict: The request could not be completed because it conflicts with the current state of the target resource.
411 — Length Required: The server refuses to accept the request without a defined Content-Length header.
415 — Unsupported Media Type: The server refuses to process the request because the request payload format is not supported.
417 — Expectation Failed: The expectation specified in the Expect request header cannot be met by the server.
421 — Misdirected Request: The request was directed to a server that is unable to produce a response for the target request.
423 — Locked: The target resource is locked.
429 — Too Many Requests: The client has sent too many requests within a given amount of time.
5xx — Server Error
Server error responses indicate that the server encountered an error or is unable to fulfill an apparently valid request.
500 — Internal Server Error: The server encountered an unexpected condition that prevented it from fulfilling the request.
501 — Not Implemented: The server does not support the functionality required to fulfill the request.
502 — Bad Gateway: The server, while acting as a gateway or proxy, received an invalid response from an upstream server.
503 — Service Unavailable: The server is currently unable to handle the request, commonly because of temporary overload or maintenance.
504 — Gateway Timeout: The server, while acting as a gateway or proxy, did not receive a timely response from an upstream server.
505 — HTTP Version Not Supported: The server does not support the HTTP protocol version used in the request.
507 — Insufficient Storage: The server is unable to store the representation needed to successfully complete the request.
511 — Network Authentication Required: The client needs to authenticate to gain network access. Question: Explain Rest Assured API testing in Java
Answer: REST Assured is a Java library that provides a domain-specific language (DSL) for testing RESTful APIs. It simplifies writing and validating API tests by offering a fluent and expressive syntax. REST Assured allows you to perform HTTP operations such as GET, POST, PUT, DELETE, and PATCH, and validate responses against expected values using assertions.
Dependency:
io.rest-assured rest-assured 6.0.1 test
Example:
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()
.statusCode(200)
.body("userId", equalTo(1))
.body("id", equalTo(1));
}
}
Question: Various methods in Rest Assured API testing in JavaAnswer: 1. Setting Up Base URI and Base Path:
baseURI(String uri): Sets the base URI for requests.
basePath(String path): Sets the base path for requests.
2. Request Specification:
given(): Starts building the request specification.
given().config(RestAssured.config()): Configures the request specification using a 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 using Hamcrest matchers. In REST Assured tests, response assertions are commonly performed through then().body() and related response validation methods.
6. Logging:
log().all(): Logs request and response details.
log().ifValidationFails(): Logs request and response details when validation fails.
log().ifError(): Logs request and response details when an error response is received.
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 a 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
10. Filters:
filter(Filter filter): Adds a filter to the request.
11. Error Handling:
REST Assured does not provide a when().error() method. Error responses can be validated using response status-code assertions and logged using methods such as log().ifError(). Exceptions thrown during request execution can be handled using standard Java exception-handling mechanisms such as try-catch.
Question: How do you log request and response details in Rest Assured?
Answer: You can log request and response details in Rest Assured using methods such as log().all(), log().ifValidationFails(), and log().ifError().
log().all(): Logs all available request or response details.
log().ifValidationFails(): Logs details when response validation fails.
log().ifError(): Logs details when an error response is received. Question: What is Rest Assured?
Answer: Rest Assured is a Java library that provides a domain-specific language (DSL) for writing powerful and maintainable tests for RESTful APIs. It simplifies the process of testing RESTful web services and supports HTTP methods such as GET, POST, PUT, DELETE, and PATCH. Question: How do you add Rest Assured to your Java project?
Answer: You can add Rest Assured to your Java project by including the dependency in your pom.xml file when using Maven or in the build.gradle file when using Gradle. The following example uses Rest Assured version 6.0.1 for Maven:
Question: How do you perform a simple GET request using Rest Assured?io.rest-assured rest-assured 6.0.1 test
Answer: You can perform a GET request using the given(), get(), and then() methods.
import static io.restassured.RestAssured.*;
public class ApiTest {
public static void main(String[] args) {
String baseURI = "https://api.example.com";
given()
.get(baseURI + "/fact")
.then()
.statusCode(200)
.log().all();
}
}
Question: How do you validate response status codes in Rest Assured?Answer: You can validate response status codes using the statusCode() method.
import static io.restassured.RestAssured.*;
public class ApiTest {
public static void main(String[] args) {
String baseURI = "https://api.example.com";
given()
.get(baseURI + "/fact")
.then()
.statusCode(200);
}
}
Question: How do you validate response body content in Rest Assured?Answer: You can validate response body content using methods such as body() and jsonPath(). For example:
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
import org.testng.annotations.Test;
public class ApiTest {
@Test
public void testApi() {
String baseURI = "https://api.example.com";
given()
.get(baseURI)
.then()
.log().all()
.statusCode(200)
.body("gender", equalTo("Value"));
}
}
Question: How do you handle authentication in Rest Assured?Answer: Rest Assured provides several methods for handling authentication, including basic authentication, OAuth, and JWT-based authentication.
import static io.restassured.RestAssured.*;
import org.testng.annotations.Test;
public class ApiTest {
@Test
public void authApi() {
String baseURI = "https://api.example.com";
given()
.auth().basic("username", "password")
.get(baseURI + "/resource")
.then()
.statusCode(200);
}
}
Question: How do you send POST requests with request parameters using Rest Assured?Answer: You can send POST requests with form parameters using the formParams() method.
import static io.restassured.RestAssured.*;
import org.testng.annotations.Test;
public class ApiTest {
@Test
public void authApi() {
String baseURI = "https://api.example.com";
given()
.formParams("param1", "value1", "param2", "value2")
.post(baseURI + "/resource")
.then()
.statusCode(200);
}
}
Question: How do you handle response headers in Rest Assured?Answer: You can access and validate response headers using the header() method.
import static io.restassured.RestAssured.*;
import org.testng.annotations.Test;
public class ApiTest {
@Test
public void testApi() {
String baseURI = "https://api.example.com";
given()
.get(baseURI + "/resource")
.then()
.header("Content-Type", "application/json")
.header("Server", "Apache");
}
}
Question: How do you handle JSON response bodies in Rest Assured?Answer: Rest Assured provides the jsonPath() method for parsing and extracting values from JSON response bodies. You can also extract the response and use JsonPath to retrieve specific values.
import static io.restassured.RestAssured.*;
import io.restassured.path.json.JsonPath;
import org.testng.annotations.Test;
public class ApiTest {
@Test
public void testApi() {
String baseURI = "https://api.example.com";
String response = given()
.get(baseURI + "/resource")
.then()
.extract()
.response()
.asString();
String value = JsonPath.from(response).getString("key");
System.out.println("Value of key: " + value);
}
}
Question: How do you handle error responses in Rest Assured?Answer: You can handle error responses by validating the expected HTTP status code and response body using then() assertions. The expect() method is not required for this purpose.
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
import org.testng.annotations.Test;
public class ApiTest {
@Test
public void testApi() {
String baseURI = "https://api.example.com";
given()
.get(baseURI + "/nonexistent-resource")
.then()
.log().all()
.statusCode(404)
.body("message", equalTo("Not Found"));
}
}
Question: How do you handle dynamic data in Rest Assured tests?Answer: Rest Assured provides several mechanisms for handling dynamic data in tests, such as path parameters, query parameters, and extracting values from response bodies and using them in subsequent requests. The following example assumes that the API returns an id field in the first element of the users response.
import static io.restassured.RestAssured.*;
import org.testng.annotations.Test;
public class ApiTest {
@Test
public void testApi() {
String baseURI = "https://api.example.com";
String userId = given()
.get(baseURI + "/users")
.then()
.extract()
.path("id[0]");
given()
.pathParam("userId", userId)
.get(baseURI + "/users/{userId}/profile")
.then()
.statusCode(200);
}
}
Question: How do you handle file uploads in Rest Assured?Answer: Rest Assured provides the multiPart() method for uploading files as part of a multipart request.
import static io.restassured.RestAssured.*;
import java.io.File;
import org.testng.annotations.Test;
public class ApiTest {
@Test
public void testApi() {
String baseURI = "https://api.example.com";
given()
.multiPart(new File("path/to/file.txt"))
.post(baseURI + "/upload")
.then()
.statusCode(200);
}
}
Question: How do you handle cookies in Rest Assured?Answer: Rest Assured provides the cookie() method for sending cookies in requests and validating cookies in responses.
import static io.restassured.RestAssured.*;
import org.testng.annotations.Test;
public class ApiTest {
@Test
public void testApi() {
String baseURI = "https://api.example.com";
given()
.cookie("sessionId", "123456789")
.get(baseURI + "/resource")
.then()
.statusCode(200)
.cookie("sessionExpires", "2024-02-14");
}
}Note: The response-cookie assertion assumes that the API actually returns a cookie named sessionExpires with the specified value. Question: How do you handle timeouts in Rest Assured?
Answer: Rest Assured allows you to configure connection and socket timeouts through its HTTP client configuration.
import static io.restassured.RestAssured.*;
import io.restassured.config.HttpClientConfig;
import org.testng.annotations.Test;
public class ApiTest {
@Test
public void testApi() {
String baseURI = "https://api.example.com";
given()
.config(config()
.httpClient(HttpClientConfig.httpClientConfig()
.setParam("http.connection.timeout", 5000)
.setParam("http.socket.timeout", 5000)))
.get(baseURI + "/resource")
.then()
.statusCode(200);
}
}
Question: How do you handle SSL certificates in Rest Assured?Answer: Rest Assured supports SSL testing with the relaxedHTTPSValidation() method. This disables SSL certificate validation and can be useful in controlled testing environments where certificate validation is intentionally not required.
Important: Do not use relaxed HTTPS validation as a general production security configuration.
import static io.restassured.RestAssured.*;
import org.testng.annotations.Test;
public class ApiTest {
@Test
public void testApi() {
String baseURI = "https://api.example.com";
given()
.relaxedHTTPSValidation()
.get(baseURI + "/resource")
.then()
.statusCode(200);
}
}
Question: How do you handle invalid input data in Rest Assured tests?Answer: Rest Assured allows you to test invalid input data by manipulating request parameters or request body content. For example, you can intentionally send malformed JSON and verify that the API returns the expected error status code.
import static io.restassured.RestAssured.*;
import org.testng.annotations.Test;
public class ApiTest {
@Test
public void testApi() {
String baseURI = "https://api.example.com";
given()
.body("{ invalid: json }")
.post(baseURI + "/resource")
.then()
.statusCode(400);
}
}Note: { invalid: json } is intentionally malformed JSON. The example assumes that the API responds with 400 Bad Request for malformed input.