6 Ways To Pass Parameters to Spring REST API
Exploring 6 ways to pass and then read the parameters in Spring Boot
Introduction
Accepting parameters that are necessary for server-side processing is fundamental requirement of REST API’s. Spring Boot with powerful capabilities for creating RESTful APIs, offers several mechanisms for passing the parameter.
In this article, we will explore 6 ways to pass parameters to the REST endpoint and how we can accept and read them in Spring Boot.
🚀 Unlock Your Path to Success with the Ultimate Everything Bundle! 🚀
Introducing the Everything Bundle — your one-stop solution to mastering Java, Spring Boot, SQL, acing interviews, and securing certifications!
1. Query Parameters
Query params are appended to the URL after the question mark (?). They are commonly used for filtering, sorting, or providing additional context to the REST endpoint.
In Spring Boot, we can access these parameters easily @RequestParam annotation.
Endpoint:
Here we are providing a getBookReviews endpoint that takes ISBN as a query parameter and returns all the book reviews for that ISBN.
@GetMapping("/reviews")
@ResponseBody()
public List<BookReview> getBookReviews(@RequestParam("isbn") String isbn){
return bookReviewsLogic.getAllReviewsByIsbn(isbn);
}
Accessing endpoint:
To access the endpoint, we are passing the query parameter after (?) and appending it to the endpoint.
curl http://localhost:8080/books/reviews?isbn=1234
2. Path Variables
Path variables are placeholders in the URI path that can be substituted with actual values when a request to the endpoint is made. They are useful for specifying unique identifiers or parameters directly in the URL.
In Spring Boot, we can capture path variables using the @PathVariable annotation.
Endpoint:
Here we are providing a getBookReviews endpoint that takes ISBN as a placeholder parameter and returns all the book reviews for that ISBN.
@GetMapping("/reviews/{isbn}")
@ResponseBody()
public List<BookReview> getBookReviews(@PathVariable String isbn){
return bookReviewsLogic.getAllReviewsByIsbn(isbn);
}
Accessing endpoint:
To access the endpoint, we are passing the actual value in the place of the placeholder.
curl localhost:8080/books/reviews/1234
3. Matrix Variables
Matrix variables allow us to pass parameters as part of the URI path, separated by a semicolon(;). This method is less common but can be useful where parameters are closer to the resource endpoint.
In Spring Boot, we can access matrix variables using @MatrixVariable annotation.
Endpoint:
Here we are providing a getBookReviews endpoint that takes ISBN and topN parameters as matrix variables and returns top N book reviews for that ISBN.
@GetMapping("/reviews")
@ResponseBody()
public List<BookReview> getBookReviews(
@MatrixVariable String isbn,
@MatrixVariable Integer topN)
{
return bookReviewsLogic.getTopNReviewsByIsbn(isbn, topN);
}
Accessing endpoint:
To access the endpoint, we are passing the parameters as semicolon-separated.
curl localhost:8080/books/reviews;isbn=1234;topN=5;
4. Request Body
Request bodies are used to send complex payloads to the POST/PUT endpoints. We can include params that we want to send in the request body itself.
In Spring Boot, we can pass the parameters within the request body using a POJO annotated with @RequestBody.
Endpoint:
Here we are providing an account add an endpoint that takes a list of Account and adds that using logic class. So if we need to send some params basically we can add that to the request body and map it to Account POJO.
@PostMapping("/add")
public boolean addAccounts(@RequestBody List<Account> accounts) throws SQLException {
accounts.stream().forEach(a -> {
a.setCreatedOn(Timestamp.from(Instant.now()));
a.setLastLogin(Timestamp.from(Instant.now()));
});
return notificationLogic.addAccounts(accounts);
}
Accessing endpoint:
To access the endpoint, we are passing the parameters as a request body (i.e. using --data ).
curl --header "Content-Type: application/json" \
--request POST \
--data '[{"username": "abcx11666111","password": "abcx117771111","email": "abcx111166611@abc.com"},{"username": "abcx28888","password": "abcx2","email": "abcx28888@abc.com"}]' \
localhost:8080/accounts/add
5. Request Headers
Request headers are used to send additional parameters along with HTTP requests. The request header can pass additional parameters like authentication tokens or metadata.
In Spring Boot, we can access request headers using @RequestHeader annotation.
Endpoint:
Here we are getting bookReviews by ISBN along with a request header auth token.
@GetMapping("/reviews/{isbn}")
@ResponseBody()
public List<BookReview> getBookReviews(@RequestHeader("Authorization") String authToken, @PathVariable String isbn){
// use authtoken to confirm authorization
return bookReviewsLogic.getAllReviewsByIsbn(isbn);
}
Accessing endpoint:
To access the endpoint, we are passing the actual value in the place of the placeholder.
curl -H "Authorization: Basic <_authToken_>" localhost:8080/books/reviews/1234
6. Cookies
This method is useful when we need to maintain stateful interaction with clients, such as keeping track of user sessions.
In Spring Boot, we can use @CookieValue annotation to extract cookie values.
Endpoint:
Here we are getting bookReviews by ISBN along with a cookie value for the sessionId of the user.
@GetMapping("/reviews/{isbn}")
@ResponseBody()
public List<BookReview> getBookReviews(@CookieValue(name = "SessionId") String sessionId, @PathVariable String isbn){
// use sessionId to retrieve valuable stateful info for current session of the user
return bookReviewsLogic.getAllReviewsByIsbn(isbn);
}
Accessing endpoint:
To access the endpoint, we pass the cookies with --cookie to the curl request.
curl --cookie "SessionId=_session_id_here" localhost:8080/books/reviews/1234
Conclusion
In this article, we explored 6 ways to pass parameters to the REST endpoint and how we can access them in Spring Boot. By leveraging these methods developers can accommodate diverse requirements, ranging from simple query parameters to complex data payload.
Become Better Dev:
To upgrade your developer skills check below resources:
Get Ready For Spring Boot Interview. | Java Interview.
Upskill SQL by Practicing it ( 20 % off with code: ABNEW20OFF )