0% found this document useful (0 votes)
52 views20 pages

API & Ms Unit5

The document outlines the key steps for creating a Spring REST controller, including the use of annotations like @RestController and @RequestMapping for defining RESTful resources and handling HTTP requests. It also discusses parameter injections in Spring REST, emphasizing the importance of data validation using annotations to ensure data integrity. Additionally, it covers strategies for building a Spring REST client and various methods for versioning REST endpoints to maintain backward compatibility.

Uploaded by

yrohini2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views20 pages

API & Ms Unit5

The document outlines the key steps for creating a Spring REST controller, including the use of annotations like @RestController and @RequestMapping for defining RESTful resources and handling HTTP requests. It also discusses parameter injections in Spring REST, emphasizing the importance of data validation using annotations to ensure data integrity. Additionally, it covers strategies for building a Spring REST client and various methods for versioning REST endpoints to maintain backward compatibility.

Uploaded by

yrohini2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

1 (a) Describe the key steps involved in creating a Spring REST controller.

 Spring provides support for creating RESTful web services using Spring MVC.
 Spring Web MVC module is the source of Spring REST as well.
 Availing this support requires Spring version 3.0 and above.
 The REST controllers are different from MVC controllers because REST controllers'
methods return results which can be mapped to a representation rather than a view.
 For this, Spring 3.0 introduced @ResponseBody annotation.
 So, the methods of REST controllers that are annotated with @ResponseBody tells
the DispatcherServlet that the result of execution need not be mapped with a view.
 @ResponseBody annotation automatically converts the response to a JSON string
literal by applying serialization on the return value of the method.
Working Internals of Spring REST:
 Spring REST requests are delegated to the DispatcherServlet that identifies the
specific controller with the help of a handler mapper.
 Then, the identified controller processes the request and renders the response.
 This response, in turn, reaches the dispatcher servlet and finally gets rendered to the
client.
Here, ViewResolver has no role to play.

What are the steps involved in exposing business functionality as a RESTful web service?
Step 1: Create a REST Resource
Step 2: Add the service methods that are mapped against the standard HTTP methods
Step 3: Configure and deploy the REST application
Since we are going to develop REST applications using Spring Boot, a lot of configurations
needed in Step-3 can be avoided as Spring Boot takes care of the same.
Creating a REST Resource
 Any class that needs to be exposed as a RESTful resource has to be annotated with
@RestController
 This annotation is used to create REST controllers.
 It is applied to a class in order to mark it as a request handler/REST resource.
 This annotation is a combination of @Controller and @ResponseBody annotations.
 @ResponseBody is responsible for the automatic conversion of the response to a
JSON string literal.
 If @Restcontroller is in place, there is no need to use @ResponseBody annotation to
denote that the Service method simply returns data, not a view.
 @RestController is an annotation that takes care of instantiating the bean and
marking the same as the REST controller.
 It belongs to the package,
org.springframework.web.bind.annotation.RestController

 @RequestMapping: This annotation is used for mapping web requests onto methods
that are available in the resource classes.
 It is capable of getting applied at both class and method levels.
 At method level, we use this annotation mostly to specify the HTTP method.

Adding request handler methods


 REST resources have handler methods with appropriate HTTP method mappings
to handle the incoming HTTP requests.
 And, this method mapping usually happens with annotations.
 For example, in the Infytel application, developed for a telecom company, we would
like to create a REST resource that can deal with operations like creating, deleting,
fetching and updating the customers.
 Here comes the summary of HTTP operations and the corresponding mappings. An
important point to be noted here is, Infytel is a Spring Boot application.
URI HTTP CustomerContr Method Annotation to be New
Metho oller method descripti applied at the Annotation
d on method level that can be
applied instead
of
@RequestMap
ping at the
method level

/custom GET fetchCustomer() Will @RequestMapping(m @GetMapping


ers fetch all ethod =
the RequestMethod.GET)
customer
s of
Infytel
App and
return the
same.

/custom POST createCustomer() Will @RequestMapping(m @PostMapping


ers create ethod =
a new RequestMethod.POS
customer T)

/custom DELET deleteCustomer() Will @RequestMapping(m @DeletMapping


ers E delete an ethod =
existing RequestMethod.DEL
customer ETE)

/custom UPDA updateCustomer( Will @RequestMapping(m @PutMapping


ers TE ) update ethod =
the RequestMethod.PUT)
details of
an
existing
customer
Configuring a REST Controller
 Since we are creating a Spring Boot application with spring-boot-starter-web
dependency, we need not pay much focus on the configurations.
 spring-boot-starter-web dependency in the pom.xml will provide the dependencies
that are required to build a Spring MVC application including the support for REST.
 Also, it will ensure that our application is deployed on an embedded Tomcat server
and we can replace this option with the one that we prefer based on the requirement

 Application class is simply annotated with @SpringBootApplication

@SpringBootApplication is a convenient annotation that adds the following:


 @Configuration marks the class as a source where bean definitions can be found for
the application context.
 @EnableAutoConfiguration tells Spring Boot to start adding beans based on the
classpath and property settings.
 @ComponentScan tells Spring to look for other components, configurations, and
services in the packages being specified.
And, one more point to be added here is,
 @EnableWebMvc is used explicitly in a regular Spring MVC application.
 But, Spring Boot adds it automatically when it sees spring-webmvc on the classpath.
 This marks the application as a web application and enables the key behaviors such as
setting up the DispatcherServlet etc.
 The main() method uses Spring Boot’s SpringApplication.run() method to launch
an application.

2(b) Illustrate the various Parameter Injections in Spring REST with


examples.
 It is not always that the client prefers sending the data as a request body.
 The client can even choose to send the data as part of the request URI.
 For example, if the client feels that the data is not sensitive and doesn't need a
separate channel to get transferred.
 So, how to receive this kind of data that appears in the URI.
 Before we look into the ways to extract the URI data, we will have a look at the
formal categorization of the data that appear in the requested URI.
1. Query Parameter
2. Path Variables
3. Matrix Variables

Query Parameter:
 Query parameters or request parameters usually travel with the URI and are delimited
by question mark.
 The query parameters in turn are delimited by ampersand from one another.
 The annotation @RequestParam helps map query/request parameters to the method
arguments.
 @RequestParam annotation expects the name that it holds to be similar to the one that
is present in the request URI.
 This makes the code tightly coupled with the request URI.
 Example: Assume, there is a RestController called CallDetailsController that has a
service method to return the call details of a specific phone number on a particular
date.
 The service method here, takes the phoneNo of the customer and the date as query
/request parameters.
Example URI:

Path Variables:
 Path variables are usually available at the end of the request URIs delimited by slash
(/).
 @Pathvariable annotation is applied on the argument of the controller method whose
value needs to be extracted out of the request URI.
 A request URI can have any number of path variables.
 Multiple path variables require the usage of multiple @PathVariable annotations.
 @Pathvariable can be used with any type of request method. For example, GET,
POST, DELETE, etc.,
We have to make sure that the name of the local parameter (int id) and the placeholder ({id})
are the same. Name of the PathVariable annotation's argument (@PathVarible("id")) and the
placeholder ({id}) should be equal, otherwise.

Example: Assume, there is a REST controller called CustomerController that has service
methods to update and delete the customers.
These operations are simply based on the phone number of the customer that is passed as part
of the request URI.
Below are the sample URIs that contain data as part of them.

The handler methods with the provision to extract the URI parameters are presented below.

Matrix variables:
 Matrix variables are a block/segment of values that travel along with the URI. For
example, /localRate=1,2,3/
 These variables may appear in the middle of the path unlike query parameters
which appear only towards the end of the URI.
 Matrix variables follow name=value format and use semicolon to get delimited from
one other matrix variable.
 A matrix variable can carry any number of values, delimited by commas.
 @MatrixVariable is used to extract the matrix variables.
If the matrix variable appears towards the end of the URI as in the below example,
We can use the following approach to read the matrix variable.

1 (b) Explain the importance of data validation in Spring REST using


annotations.
Need for Validation:
 Sometimes, the RESTful web service might need data in certain standards that should
pass through specific constraints.
 What if the data is not in the format as needed by the RESTful service?
By default, Spring Boot provides some implementation for validation
 415 - Unsupported Media Type : If the data is sent in a different format other than
what is expected(eg:XML instead of JSON)
 400 - Bad Request : If JSON data is not in proper format, for example.
Sometimes, we might send valid format and structure, but with missing data. Still, the request
gets processed. In such situations, it becomes even more important to validate the data.
Example:
1. {
2. //empty JSON data
3. }
Hibernate Validator, is one of the implementations of the bean validation API.
Bean Validation API provides a number of annotations and most of these annotations are self
explanatory.
 Digits
 Email
 Max
 Min
 NotEmpty
 NotNull
 Null
 Pattern
● @Email validates that the annotated property is a valid email address.
● @Max validates that the annotated property has a value no larger than the value attribute.
● @Min Validates that the annotated property has a value no smaller than the value attribute.
● @NotEmpty Validates that the property is not null or empty; can be applied to String,
Collection, Map or Array values.
● @NotNull Validates that the annotated property value is not null.
Class Customer{
@Email
private String email;
@NotBlank
private String name;

}

Applying validation on the incoming data


 Let us apply validation on the customer data that comes to the createCustomer()
method of CustomerController.
 Infytel expects the name field not to be null and the email field to be of proper email
format.

 Have a look at the usage of @NotNull and @Email on the fields, name and email
respectively.
 Adding the constraints simply on the bean will not carry out validation.
 In addition, we need to mention that validation is required while the JSON data is
deserialized to CustomerDTO and get the validation error, if any,
into org.springframework.validation.Errors object.
 This can be done by applying @Valid annotation on the handler method argument
which captures the CustomerDTO object as shown below.
 We can inject the Errors object too into this method.
Discussion on how the validation takes place
@Valid @RequestBody CustomerDTO customerDTO - indicates that CustomerDTO
should be validated before being taken.
Errors - indicates the violations, if any, to get stored in the Errors object.
Finally, the business logic will be divided into two courses of actions.
That is, what should be done when there are no validation errors.
And, what should be done, otherwise.
1. If there are errors:
 Collect all the errors together as a String.
 Set the String that contains errors in the message field and appropriate error code in
the errorCode field of ErrorMessage.
 Finally, return the ResponseEntity that is set with the ErrorMessage object.
The ErrorMessage class:

2. If there are no errors, invoke the service layer to create the customer and return the
response back to the client.
We are done dealing with validating the incoming objects/DTOs.
Also, we finished traversing a set of annotations that impose validation on the individual
fields/attributes of the DTO.
Apart from the annotations that we discussed, we have few other interesting annotations in
place. For example,
@PastOrPresent
@Past
@Future
@FutureOrPresent
@DateTimeFormat - part of org.springframework.format.annotation unlike other
annotations being mentioned here which are part of standard javax.validation.constraints
URI parameter validation
 Like how it is important to validate the incoming objects/DTOs, it is essential to
validate the incoming URI parameters as well.
 For example, when the customer details need to be deleted based on the phone
number and if the same is reaching the REST endpoint as URI parameter (path
variable, for example), it becomes essential that the URI parameter, phone number
should also be validated (should be of 10 digits, for example).
The code snippet given below helps serve the purpose discussed above.

 One important thing that needs attention while validating the URI parameters is,
@Validated.
 The controller where the URI parameter validation is carried out should be
annotated with @Validated.
 The validation on URI parameters will not be triggered, otherwise.
 Here, the CustomerController has validations pertaining to phoneNo that is received
as a URI parameter (DELETE and UPDATE).
 So, @Validated annotation needs to be applied on the same as follows.
3(b) Outline a strategy to build a Spring REST client.
 There are situations where a Spring REST endpoint might be in need of contacting
other RESTful resources.
 Situations like this can be handled with the help of a REST client that is available in
the Spring framework.
 And, the name of this REST client is RestTemplate.
 RestTemplate has wonderful support for standard HTTP methods.
 The methods of the RestTemplate need to be provided with the absolute URI where
the service can be found, input data, if any and, the response type that is expected out
of the service.
Calling a RESTful service of HTTP request method Get:
The following code snippet shows how to consume a RESTful service exposed by url
:http://localhost:8080/infytel/customers using HTTP GET.

Calling a RESTful service of HTTP request method Post:


URI of the service:http://localhost:8080/infytel/customers

Similarly, RESTful services of various other HTTP methods can be called using
RestTemplate.
2(a) Demonstrate Spring REST endpoint versioning with examples
using URL, custom headers, or media types.
Versioning a REST endpoint
 Versioning a service becomes important when we want to create a new version of an
already existing service.
 But at the same time, we need to support the earlier version as well, to ensure
backward compatibility.
There are different ways of achieving API versioning such as
 URI versioning
 Request Parameter Versioning
 Custom Header Versioning
 Accept Header versioning
URI versioning
 URI versioning involves different URIs for every newer version of the API.
 Example: There is a need for two versions of functionality that fetches the plan details
of Infytel telecom application. And, this fetch operation is based on the planId being
passed as a path variable.
version-1: Fetches the complete plan details that include plainId, planName, localRate and
nationalRate
version-2: Fetches only the localRate and nationalRate.
Below is the URI proposed to be used

Now, let us look at how the handler method can be written.


For Version-1
For Version-2

Versioning with Custom Headers


 This type of versioning requires the inclusion of custom headers in the request URI to
map to the correct version of the API endpoint.
 Let us take the service that fetches plan details, here as well.
Below is the URI proposed to be used

Now, let us look at how the handler method can be written


For Version-1

For Version-2
Accept Header Versioning
 Accept Header Versioning approach is one other way of versioning the API methods
that insists the usage of Accept Header in the request.

Now, let us look at how the handler method can be written


For Version-1

For Version-2

Request Parameter versioning


Request parameter versioning can be achieved by providing the request parameter in the URI
that holds the version details.
Now, let us look at how the handler method can be written
For Version-1

For Version-2

3(a) Explain enabling CORS in Spring REST concisely, ensuring secure


cross-origin requests within the service.
 Typically, scripts running in a web application of one origin (domain) cannot have
access to the resources of a server available at a different origin.
 If the clients of different origins try to access the REST endpoints of an application,
CORS error will be thrown simply. And, below is a sample of the same.

Look at the image below, which depicts the request for resources by the clients of the same
origin and different origins as well.
Requests for resources from a different domain will encounter CORS error.
To overcome this error, we need to enable cross-origin requests at the server-side so that the
browsers which run the client code can allow scripts to make a Cross-origin call
Cross-origin calls can be enabled for Spring REST resources in three ways by applying:
 CORS configuration on the REST controller methods
 CORS configuration on the REST controller itself
 CORS configuration globally (common to the entire application)
CORS configuration on controller methods:
In this style, we need to apply @CrossOrigin on the handler method.
Here, the annotation @CrossOrigin enables cross-origin requests only for the specific handler
method.
By default, it allows all origins, all headers, all HTTP methods specified in the
@RequestMapping annotation. Also, a lot more other defaults are available.
We can customize this behavior by specifying the value for the following attributes that are
available with Http method mapping annotations (@GetMapping, @PostMapping, etc.,)
 origins - list of allowed origins to access the method
 methods - list of supported HTTP request methods
 allowedHeaders - list of request headers which can be used during the request
 exposedHeaders - list of response headers which the browser can allow the clients to
access
 allowCredentials - determines whether the browser can include cookies that are
associated with the request
Example:
CORS configuration on the controller:
It is possible to add @CrossOrigin at the controller level as well, to enable CORS for all the
handler methods of that particular controller.

Global CORS configuration:


As an alternative to fine-grained, annotation-based configuration, we can also go for global
CORS configuration as well.
Look at the code below. The starter class has been modified to implement
WebMvcConfigurer and override addCorsMappings() method that takes the CorsRegistry
object as argument using which we can configure the allowed set of domains and HTTP
methods as well.

You might also like