Add URI Parameters to Spring WebClient Requests

Examples of Adding Requests Parameters like URI Path Parameters and Query Parameters in Spring WebClient requests.

Overview

Spring WebClient is a reactive and non-blocking client for making HTTP requests. This client is part of the Spring WebFlux library, and as per the recent updates, it will replace the traditional RestTemplate client. In contrast to the RestTemplate, WebClient offers the flexibility of using a builder pattern to build and execute requests. Also, the WebClient allow blocking or a non-blocking style of request execution.

In this tutorial, we will learn to pass URI Parameters (path parameters and query parameters) in WebClient Requests. Before we do that, let’s understand URI Parameters and examples of different types of parameters.

URI Parameters in Requests

The Request URI parameters help identify particular resources on the server, specify certain filters on the response, or pass some information to the server. There are three types of request parameters – Path Parameters, Query Parameters, and Header Parameters. However, this tutorial focuses on Request URI parameters, path parameters or path variables and query parameters.

Path Parameters

The Path Parameters are request parameters appearing on a Request URI’s path. They are also known as Path Variables or Path Segments. They help to bind the Request to a specific resource(s).

For example,

  • GET /students
  • GET /students/{studentId}
  • GET /students/{studentId}/assignments/{assignmentId}

The first endpoint maps to all students on the server. Hence the server should return all students in the response. However, the second endpoint has a path variable to identify a particular student. Similarly, the third endpoint has nested path variables, which map to a particular assignment of a particular student.

Query Parameters

The Query Parameters or Query String Parameters are key and value pairs separated by an ampersand (&), and they appear at the end of a URL after a question mark (?). The Query Parameters are an extension to Path variables and are usually used to put additional filters on the resource.

For example,

  • GET /students?firstName=Jon&year=1995
  • GET /students?year=1995&year=1996&year=1997

In the first one, the endpoint finds students by firstName and year. Similarly, the second one returns students by an array of years.

The following sections will show how to pass Path Variables and Query Strings using Spring WebFlux WebClient.

Path Parameters in WebClient

Let’s use WebClient to access a resource endpoint without passing any path variable or parameter.

WebClient.create("http://localhost:8080")
    .get()
    .uri("/students")
    .retrieve()
    .bodyToFlux(Student.class);Code language: Java (java)

This returns a Flux of all students. Now, let’s add a path variable to narrow the Request to a specific resource.

Path Parameter using String Concatenation

The simplest and the most basic method of adding a path parameter or URI component to a request URI is to use String concatenation.

WebClient.create("http://localhost:8080")
    .get()
    .uri("/students/" + studentId)
    .retrieve()
    .bodyToMono(Student.class);Code language: Java (java)

Path Parameter using UriBuilder

Alternatively, we can use Spring UriBuilder to build a URI with a Path Variable or Path Segment.

WebClient.create("http://localhost:8080")
    .get()
    .uri(uriBuilder -> uriBuilder
        .path("/student/{studentId}")
        .build(studentId))
    .retrieve()
    .bodyToMono(Student.class);Code language: Java (java)

The UriBuilder function replaces the {studentId} token with the value provided in the build() method.

Similarly, we can use the UriBuilder to build a URI with multiple path variables that access a nested resource on the server.

WebClient.create("http://localhost:8080")
    .get()
    .uri(uriBuilder -> uriBuilder
        .path("/student/{studentId}/assignments/{assignmentId}")
        .build(studentId, assignmentId))
    .retrieve()
    .bodyToMono(Student.class);Code language: Java (java)

The example shows executing an endpoint with two path parameters. We have provided two values to the build() method. The UriBuilder sequentially replace them in the URI from left to right.

Path Parameter using UriTemplate

Similarly, we can use Spring UriTemplate to build a URI with zero or more path parameters. Using it, we can create a URI template once and use it with different values to access other resources.

Firstly, we will create an instance of UriTemplate by providing a templated URI in the form of a string.

UriTemplate uriTemplate = new UriTemplate(
    "/student/{studentId}/assignments/{assignmentId}");Code language: Java (java)

Next, we can use the UriTempalte in WebFlux WebClient and provide path parameters.

WebClient.create("http://localhost:8080")
    .get()
    .uri(uriTemplate.expand(studentId, assignmentId))
    .retrieve()
    .bodyToMono(Student.class);Code language: Java (java)

A new URI instance is returned every time we invoke the expand method. That means we can reuse the same URI Template to make different requests with different path variable values.

Query Parameters in WebClient

Similar to the path parameters, we can use String concatenation or UriTemplate to attach query parameters. However, using the UriBuilder to pass query parameters is slightly different than path variables. Thus, we will focus on using UriBuilder.

Single Value

To pass single-value query parameters, create a path of the base resource URI and then use the queryParam() method to append key-value pairs.

String firstName = "Jon";
String year = "1996";

WebClient.create("http://localhost:8080")
    .get()
    .uri(uriBuilder -> uriBuilder.path("/students")
        .queryParam("firstName", firstName)
        .queryParam("year", year)
        .build())
    .retrieve()
    .bodyToMono(Student.class);Code language: Java (java)

The final URL that the WebClient executes will be

http://localhost:8080/students?firstName=Jon&year=1996Code language: plaintext (plaintext)

Multiple Values or Arrays

If a query parameter in a URI has multiple values, then the parameter appears multiple times with different values. To do that with UriBuilder, we can pass all those values into the queryParam() method.

WebClient.create("http://localhost:8080")
    .get()
    .uri(uriBuilder -> uriBuilder.path("/students")
        .queryParam("year", 1995, 1996, 1997)
        .build())
    .retrieve()
    .bodyToMono(Student.class);Code language: Java (java)

The example shows passing an array as a query String in WebClient. The final URL looks like this.

http://localhost:8080/students?year=1995&year=1996&year=1997Code language: plaintext (plaintext)

Comma Separated Value

Lastly, to send a query parameter having comma-separated values, we can join multiple String values with commas.

WebClient.create("http://localhost:8080")
    .get()
    .uri(uriBuilder -> uriBuilder.path("/students")
        .queryParam("year", String.join(",", "1995", "1996", "1997"))
        .build())
    .retrieve()
    .bodyToMono(Student.class);Code language: Java (java)

The final URL looks as shown in the following snippet.

http://localhost:8080/students?year=1995,1996,1997Code language: plaintext (plaintext)

Summary

This tutorial discussed How to pass URI Parameters in Spring WebFlux WebClient Requests and offered many examples of passing path parameters and request query string parameters to a WebClient Request.

To summarize, we started with an introduction to request URI parameters – path parameters or path segments and query strings with examples. Then we learned how to use String concatenation, UriBuilder, and UriTemplate to add path parameters in WebClient. Lastly, we learned to pass single-value query parameters, multi-value query parameters, and query parameters with comma-separated values.