WT Unit 5 Part D Mca Mit

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

MARATHWADA INSTITUTE OF TECHNOLOGY, BULANDSHAHR

DEPARTMENT OF MCA
SUBJECT NOTES (WEB TECHNOLOGY- KCA 021)
(PROF. AVNISH KR. SHARMA)

UNIT -3 (PART A)
UNIT 5 PART D

Spring Boot – @PathVariable and @RequestParam


Annotations


When building RESTful APIs with Spring Boot, it’s crucial to extract data from
incoming HTTP requests to process and respond accordingly. The Spring framework
provides two main annotations for this purpose: @PathVariable and @RequestParam.
 The @PathVariable annotation is used to retrieve data from the URL path. By
defining placeholders in the request mapping URL, you can bind those
placeholders to method parameters annotated with @PathVariable. This allows
you to access dynamic values from the URL and use them in your code. For
example, you can extract a user ID from a URL like /users/123 and pass it to a
method that retrieves the corresponding user’s details.
 On the other hand, the @RequestParam annotation enables you to extract data
from the query parameters in the request URL. Query parameters are key-value
pairs appended to the URL after a question mark (?). With @RequestParam, you
can specify the name of the parameter to retrieve and bind it to a method
parameter. This is useful when you need to pass additional information or filters to
your API endpoints. For instance, you can extract the value of a name parameter
from a URL like /users/search?name=John and use it to search for users with the
given name.
 Both @PathVariable and @RequestParam annotations simplify the process of
extracting data from incoming requests in Spring Boot. They provide a clean and
declarative way to access dynamic values from URLs and query parameters,
making it easier to handle and process request data in your REST API endpoints.
By leveraging these annotations effectively, you can enhance the functionality of your
Spring Boot applications, create more flexible APIs, and provide better user

1|Page
MCA DEPARTMENT MIT BULANDSHAHR
experiences by allowing clients to pass relevant data in their requests. Here’s a
detailed explanation of the @PathVariable and @RequestParam annotations in Spring
Boot, along with full source code examples:

Using @PathVariable
The @PathVariable annotation is used to extract data from the URL path. It allows
you to define placeholders in your request mapping URL and bind those placeholders
to method parameters. Let’s consider an example where you have a REST API
endpoint for retrieving a user’s details by their ID:

 Java

@RestController

@RequestMapping("/users")

public class UserController {

@GetMapping("/{userId}")

public ResponseEntity<User> getUserDetails(@PathVariable Long userId) {

// Implementation to fetch user details based on the provided


userId

// ...

return ResponseEntity.ok(user);

In the above code, the @PathVariable annotation is used to extract the userId from the
URL path. The {userId} placeholder is defined in the @GetMapping annotation’s
URL mapping. The value of the {userId} placeholder will be extracted and passed as
the userId method parameter. When a request is made to /users/123, the value 123 will
be passed to the getUserDetails method as the userId parameter. You can then use this
ID to fetch the user details from a database or any other data source.

Using @RequestParam

2|Page
MCA DEPARTMENT MIT BULANDSHAHR
The @RequestParam annotation is used to extract data from the query parameters in
the request URL. Query parameters are the key-value pairs that appear after the ? in a
URL. Let’s consider an example where you have a REST API endpoint for searching
users based on a query parameter:

 Java

@RestController

@RequestMapping("/users")

public class UserController {

@GetMapping("/search")

public ResponseEntity<List<User>> searchUsers(@RequestParam("name")


String name) {

// Implementation to search users based on the provided name

// ...

return ResponseEntity.ok(users);

In the above code, the @RequestParam annotation is used to extract the name
parameter from the query parameters. The name parameter is specified as an argument
of the @RequestParam annotation. When a request is made to
/users/search?name=John, the value John will be passed to the searchUsers method as
the name parameter. You can then use this parameter to perform a search operation
based on the provided name.
You can also specify optional parameters by setting the required attribute of
@RequestParam to false. Additionally, you can provide default values using the
defaultValue attribute. Here’s an example that demonstrates how to specify optional
parameters using the @RequestParam annotation in Spring Boot and provide default
values using the defaultValue attribute:

 Java

3|Page
MCA DEPARTMENT MIT BULANDSHAHR
@RestController

@RequestMapping("/users")

public class UserController {

@GetMapping("/search")

public ResponseEntity<List<User>> searchUsers(

@RequestParam(value = "name", required = false, defaultValue =


"John") String name,

@RequestParam(value = "age", required = false, defaultValue =


"18") int age) {

// Implementation to search users based on the provided name and


age

// ...

return ResponseEntity.ok(users);

In the above code, the searchUsers method accepts two query parameters: name and
age. Both parameters are annotated with @RequestParam and have optional
configurations. The name parameter is specified with required = false, indicating that
it is optional. If the name parameter is not provided in the request URL, the default
value “John” will be used.
The age parameter is also specified with required = false, making it optional. In
addition, it has a default value of 18 specified using defaultValue = “18”. If the age
parameter is not provided in the request URL, the default value of 18 will be used.
Additional points to consider regarding the topic of extracting request data using
@PathVariable and @RequestParam annotations in Spring Boot:
1. Data Type Conversion: Spring Boot provides automatic data type conversion for
@PathVariable and @RequestParam parameters. It can convert the incoming
4|Page
MCA DEPARTMENT MIT BULANDSHAHR
request data to the required data types, such as String, int, boolean, etc. If the
conversion fails, it will throw an exception, allowing you to handle the error
gracefully.
2. Multiple Parameters: You can use multiple @PathVariable and @RequestParam
annotations in a single method to extract multiple values from the URL path and
query parameters. This allows you to retrieve and utilize multiple data points from
a single request.
3. Data Validation: You can apply validation on the extracted request data by using
validation annotations from the javax.validation package or custom validation
logic. This helps ensure that the provided data meets specific criteria before
processing it further.
4. Path Variable Patterns: The @PathVariable annotation supports variable patterns
within the URL path. You can define placeholders with regular expressions to
match specific patterns and extract the corresponding values. This can be useful
for handling dynamic and complex URL structures.
5. Query Parameter Collections: If you expect multiple values for a query parameter,
you can use List or Array types for the corresponding method parameter annotated
with @RequestParam. Spring Boot will automatically bind all the values to the
collection parameter.
6. Optional Path Variables: You can make path variables optional by providing a
default value or using the Optional<T> type as the method parameter. This allows
you to handle cases where certain path variables may or may not be present in the
request.
7. Remember to handle potential exceptions and error scenarios appropriately when
extracting request data. Spring Boot provides various mechanisms, such as
exception handlers, to handle and customize error responses based on your
application’s requirements.
By leveraging the power of @PathVariable and @RequestParam annotations, you can
effectively extract and process request data in your Spring Boot applications, making
your REST API endpoints more dynamic and versatile. Here’s the full source code for
a Spring Boot application that demonstrates the usage of @PathVariable and
@RequestParam annotations:

 Java

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.GetMapping;

5|Page
MCA DEPARTMENT MIT BULANDSHAHR
import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;

import java.util.List;

@SpringBootApplication

public class Application {

public static void main(String[] args) {

SpringApplication.run(Application.class, args);

@RestController

@RequestMapping("/users")

class UserController {

@GetMapping("/{userId}")

public ResponseEntity<String> getUserDetails(@PathVariable Long userId)

6|Page
MCA DEPARTMENT MIT BULANDSHAHR
{

// Implementation to fetch user details based on the provided


userId

String userDetails = "User details for user ID: " + userId;

return ResponseEntity.ok(userDetails);

@GetMapping("/search")

public ResponseEntity<List<String>> searchUsers(@RequestParam("name")

String name) {

// Implementation to search users based on the provided name

List<String> users = Arrays.asList("John", "Jane", "Robert");

return ResponseEntity.ok(users);

Explanation

 The Application class is the entry point for the Spring Boot application. It is
annotated with @SpringBootApplication.
 The UserController class is annotated with @RestController, indicating that it is a
REST controller.
 The base URL path for all user-related endpoints are defined using
@RequestMapping(“/users”).
 The getUserDetails method is mapped to the /{userId} URL pattern using
@GetMapping(“/{userId}”). The userId path variable is extracted using
@PathVariable and passed as a method parameter.
 The searchUsers method is mapped to the /search URL pattern using
@GetMapping(“/search”). The name query parameter is extracted using
@RequestParam(“name”) and passed as a method parameter.

7|Page
MCA DEPARTMENT MIT BULANDSHAHR
 You can run this Spring Boot application, and it will provide two endpoints:
/users/{userId} and /users/search. You can send requests to these endpoints with
appropriate path variables and query parameters to see the respective data
extraction in action.

REST API Introduction


Representational State Transfer (REST) is an architectural style that defines a set of
constraints to be used for creating web services. REST API is a way of accessing web
services in a simple and flexible way without having any processing.

REST technology is generally preferred to the more robust Simple Object Access
Protocol (SOAP) technology because REST uses less bandwidth, simple and flexible
making it more suitable for internet usage. It’s used to fetch or give some information
from a web service. All communication done via REST API uses only HTTP request.
Working: A request is sent from client to server in the form of a web URL as HTTP
GET or POST or PUT or DELETE request. After that, a response comes back from
the server in the form of a resource which can be anything like HTML, XML, Image,

8|Page
MCA DEPARTMENT MIT BULANDSHAHR
or JSON. But now JSON is the most popular format being used in Web Services.

In HTTP there are five methods that are commonly used in a REST-based
Architecture i.e., POST, GET, PUT, PATCH, and DELETE. These correspond to
create, read, update, and delete (or CRUD) operations respectively. There are other
methods which are less frequently used like OPTIONS and HEAD.
 GET: The HTTP GET method is used to read (or retrieve) a representation of a
resource. In the safe path, GET returns a representation in XML or JSON and an
HTTP response code of 200 (OK). In an error case, it most often returns a 404
(NOT FOUND) or 400 (BAD REQUEST).

 POST: The POST verb is most often utilized to create new resources. In
particular, it’s used to create subordinate resources. That is, subordinate to some
other (e.g. parent) resource. On successful creation, return HTTP status 201,
returning a Location header with a link to the newly-created resource with the 201
HTTP status.
NOTE: POST is neither safe nor idempotent.
 PUT: It is used for updating the capabilities. However, PUT can also be used
to create a resource in the case where the resource ID is chosen by the client
instead of by the server. In other words, if the PUT is to a URI that contains the
value of a non-existent resource ID. On successful update, return 200 (or 204 if not
returning any content in the body) from a PUT. If using PUT for create, return
HTTP status 201 on successful creation. PUT is not safe operation but it’s
idempotent.
 PATCH: It is used to modify capabilities. The PATCH request only needs to
contain the changes to the resource, not the complete resource. This resembles
PUT, but the body contains a set of instructions describing how a resource
currently residing on the server should be modified to produce a new version. This
means that the PATCH body should not just be a modified part of the resource, but
in some kind of patch language like JSON Patch or XML Patch. PATCH is neither
safe nor idempotent.
 DELETE: It is used to delete a resource identified by a URI. On successful
deletion, return HTTP status 200 (OK) along with a response body.
Idempotence: An idempotent HTTP method is a HTTP method that can be called
many times without different outcomes. It would not matter if the method is called

9|Page
MCA DEPARTMENT MIT BULANDSHAHR
only once, or ten times over. The result should be the same. Again, this only applies to
the result, not the resource itself.
Example:
 C

1. a = 4 // It is Idempotence, as final value(a = 4)

// would not change after executing it multiple

// times.

2. a++ // It is not Idempotence because the final value

// will depend upon the number of times the

// statement is executed.

Request and Response


Now we will see how request and response work for different HTTP methods. Let’s
assume we have an API(https://www.geeksforgeeks.org/api/students) for all students
data of gfg.
 GET: Request for all Students.

Request

GET:/api/students

 POST: Request for Posting/Creating/Inserting Data


Request

POST:/api/students
{“name”:”Raj”}

 PUT or PATCH: Request for Updating Data at id=1


Request

PUT or PATCH:/api/students/1
{“name”:”Raj”}

 DELETE: Request for Deleting Data of id=1


10 | P a g e
MCA DEPARTMENT MIT BULANDSHAHR
Request

DELETE:/api/students/1

RESTful web services are very popular because they are light weight, highly scalable
and maintainable and are very commonly used to create APIs for web-based
applications.

11 | P a g e
MCA DEPARTMENT MIT BULANDSHAHR

You might also like