Skip to main content

API Questions

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:

  1. 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.


  2. 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.


  3. 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.


  4. 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?

Answer: Latency refers to the response time or the delay taken by the request to reach the server. We need to ensure that the latency involved in reaching the server is minimum as higher the latency, greater is the impact in the application’s speed and performance.


Question:  Key components of ReadyAPI and how they contribute to API testing
Answer: Certainly! ReadyAPI is a comprehensive API testing tool that offers various key 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 all the artifacts related to API testing. It allows you to organize your 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 the 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 like 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 (e.g., development, staging, 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 like 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 the test results, including pass/fail status, response data, and logs. Reports are crucial for tracking the health of your APIs and debugging any issues.

10. Integration: ReadyAPI seamlessly 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, ensuring the reliability and quality of web services.

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>


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()

    //.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.

Question: How do you add RestAssured to your Java project
Answer: You can add RestAssured to your Java project by including the dependency in your project's pom.xml file if you're using Maven or in the build.gradle file if you're using Gradle. Here's an example for Maven:

<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>5.3.2</version>
    <scope>test</scope>
</dependency>

Question: How do you perform a simple GET request using RestAssured?
Answer: 

import  io.restassured.RestAssured.*;

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

}

}


Question: How do you validate response status codes in RestAssured?
Answer: You can validate response status codes using the statusCode() method.


    public static void main(String[] args) {
        String baseURI = "https://api.example.com";

        RestAssured.

given()

.get(baseURI+"/fact")

.then()

.statusCode(200) // Validates if the response status code is 200

    }


Question: How do you validate response body content in RestAssured?
Answer: You can validate response body content using various methods like body(), jsonPath()


    @Test
public void testApi() {
        baseURI = "https://api.example.com";
        
        // Perform GET request

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

        
    }



Question: How do you handle authentication in RestAssured?
Answer: RestAssured provides several methods for handling authentication, including basic authentication, OAuth, and JWT authentication.

@Test

public void authApi() {

baseURI = "https://api.example.com";


RestAssured.

given()

.auth().basic("username", "password")

.get("/resource")

.then()

.statusCode(200);

}



Question: How do you send POST requests with request parameters using RestAssured?
Answer: You can send POST requests with request parameters using the formParams() method.


@Test

public void authApi() {

baseURI = "https://api.example.com";


RestAssured

.given()

.formParams("param1", "value1", "param2", "value2")

.post("/resource")

.then()

.statusCode(200);

}



Question: How do you handle response headers in RestAssured?
Answer: You can access and validate response headers using the header() method.

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

}

}


Question: How do you handle JSON response bodies in RestAssured?
Answer: RestAssured provides the jsonPath() method for parsing and extracting values from JSON response bodies.

@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);

}



Question: How do you handle error responses in RestAssured?
Answer: You can handle error responses using the expect() method to specify expected error codes and messages.


@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"));

}


Question: How do you handle dynamic data in RestAssured tests?
Answer: RestAssured provides several mechanisms for handling dynamic data in tests, such as using path parameters, query parameters, or extracting values from response bodies and using them in subsequent requests. Here's an example of extracting a value from a response and using it in a subsequent request:


@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);

}



Question: How do you handle file uploads in RestAssured?
Answer: RestAssured provides the multiPart() method for uploading files as part of a multipart request.
import static io.restassured.RestAssured.*;
import java.io.File;

@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);

}


Question: How do you handle cookies in RestAssured?
Answer: RestAssured provides the cookie() method for handling cookies in requests and responses. 

@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");

}



Question: How do you handle timeouts in RestAssured?
Answer: RestAssured allows you to specify connection and request timeouts using the config() method. 

@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);

}



Question: How do you handle SSL certificates in RestAssured?
Answer: 
RestAssured supports handling SSL certificates using the relaxedHTTPSValidation() method to disable SSL certificate validation. 

@Test

public void testApi() {

String baseURI = "https://api.example.com";


RestAssured. given()

.relaxedHTTPSValidation()

.get("/resource")

.then()

.statusCode(200);

}


Question: How do you handle invalid input data in RestAssured tests?
Answer:  RestAssured allows you to simulate sending invalid input data by manipulating request parameters or body content. 
Here's an example of sending an invalid JSON payload:

@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

popular

Privacy policy for Sri Bhagavat Gita

 Privacy Policy for Sri Bhagavad Gita This respects the privacy of its users and is committed to protecting their personal information. This privacy policy outlines the information collected by This and how it is used. Information We Collect : We are not collecting any personal information such as name and email address. This may collect non-personal information such as device type, operating system version, and app usage data to improve the app's functionality and user experience. Sharing of Information This does not sell or share personal information with third parties for marketing purposes. This may share personal information with service providers for the purpose of providing registration or support services to the user. Security of Information This takes reasonable measures to protect user data against unauthorized access, alteration, or destruction. However, This cannot guarantee the security of user data transmitted over the internet. Children's Privacy This does not kn

Privacy policy for BMI calculator

Privacy Policy for BMI Calculator  Effective Date: 5th July 2023 1.1 Personal Information: We do not collect any personally identifiable information (PII) such as your name, address, email, or phone number when you use the App. 1.2 Non-Personal Information: The App may collect certain non-personal information automatically, such as your device's unique identifier (UDID), device type, operating system, language preferences, and anonymous usage statistics. This information is collected to improve the functionality and user experience of the App and is not linked to any personally identifiable information. 2. Use of Information: 2.1 Personal Information: As stated earlier, we do not collect any personal information through the App. Therefore, we do not use or share any personal information. 2.2 Non-Personal Information: The non-personal information collected by the App may be used for the following purposes: - To improve the performance, functionality, and user experience of the App.

privacy policy for Selenium App

 Effective Date: 16 Sep 2023 URL -  https://play.google.com/store/apps/details?id=com.csj.selenium 1. Introduction :   This Privacy Policy outlines how we collect, use, disclose, and safeguard your personal information when you use our Android application ("App"). By accessing or using the App, you agree to the terms and practices described in this Privacy Policy. If you do not agree with our policies and practices, please do not use the App. 2. Information We Collect : - 2.1. Personal Information: We do not collect any personal information from you directly. However, we may collect non-personal information such as device information (e.g., device type, operating system, unique device identifier), and usage data (e.g., pages visited, interactions within the App). 2.2. User-Generated Content: The App allows you to submit questions and answers. Any content you submit will be stored on your local device.  3. How We Use Your Information -We may use non-personal information for an