Async Requests
Explore how to handle asynchronous requests in REST API automation using Rest Assured along with the AsyncHttpClient library. Understand the difference between synchronous and asynchronous calls, how to implement async requests in Java, manage timeouts, and retrieve responses effectively in test automation scenarios.
We'll cover the following...
What is an async request?
Synchronous request blocks the execution of server code until the response is received, whereas asynchronous request (async in short), does not block the execution and returns a callback to the client which can be used to receive the actual data once the execution is complete.
Handling async requests
REST Assured does not support async requests out of the box. We can automate these use cases using a third-party open-source library.
We will be using asynchttpclient for the same and to use this, let’s add below dependency to our build file.
Maven
Add this in the pom.xml file:
<dependency>
<groupId>org.asynchttpclient</groupId>
<artifactId>async-http-client</artifactId>
<version>2.12.0</version>
</dependency>
Gradle
Add this in the build.gradle file:
compile group: 'org.asynchttpclient', name: 'async-http-client', version: '2.12.0'
Let’s now understand how we can handle async requests using the code below:
Let’s understand the code above
-
Target URL sends back the response after a delay of 3 secs
String url = "https://reqres.in/api/users?delay=3"; -
Creates an object of
Futureof typeResponseand makes a GET call using theprepareGet(url)methodFuture<Response> whenResponse = Dsl.asyncHttpClient().prepareGet(url).execute(); -
Using the
FutureResponse above, it waits if necessary, for the computation to complete, and then retrieves its result until the future returns responseResponse response = whenResponse.get();To wait with a maximum timeout, we can use the code below:
Response response = whenResponse.get(10, TimeUnit.SECONDS);If Future does not complete (or if we don’t receive response) with 10 seconds, we get
java.util.concurrent.TimeoutException.
In the next lesson, we will learn about proxy server settings.