1 SIR C R REDDY COLLEGE OF ENGINEERING, ELURU
API & MICROSERVICES Unit-5 Dept. of CSE, j s v g k r i s h n a
UNIT V
Spring REST: Spring REST - An Introduction, Creating a Spring REST Controller, @RequestBody
and ResponseEntity, Parameter Injection, Usage of @PathVariable, @RequestParam and
@MatrixVariable, Exception Handling, Data Validation, Creating a REST Client, Versioning a
Spring REST endpoint, Enabling CORS in Spring REST, Securing Spring REST endpoints
Hardware and software configuration - 4 or 8 GB RAM/126 GB ROM - Swagger tool
suite(opensource) - OpenJDK 17 or Java 11,Maven 3.2 or above and MySQL 8.0 or above,Spring
Tool suite, Postman
Sring REST
1: Sring REST- An Introduction:
Creating a Spring REST Controller
Creating RESTful services is a fundamental aspect of modern web applications and microservices
architectures. Spring Boot, combined with Spring Web MVC (also known as Spring REST),
provides a powerful and easy-to-use framework for building RESTful APIs. In this module, we will
explore how to create a Spring REST Controller, which is the core component for handling HTTP
requests and responses in a RESTful service.
What is a REST Controller?
A REST Controller in Spring Boot is a specialized version of a Spring MVC controller. It is
annotated with @RestController, which is a convenience annotation that
combines @Controller and @ResponseBody. This means that the methods in
a @RestController return data directly in the response body, typically in JSON or XML format,
rather than rendering a view.Key Characteristics:
Stateless: Each request from a client to a server must contain all the information needed to
understand and process the request.
2 SIR C R REDDY COLLEGE OF ENGINEERING, ELURU
API & MICROSERVICES Unit-5 Dept. of CSE, j s v g k r i s h n a
Resource-Based: Resources are identified by URIs, and interactions with these resources are
performed using standard HTTP methods (GET, POST, PUT, DELETE).
Representation: Resources can have multiple representations, such as JSON, XML, or HTML.
Setting Up a Spring Boot Project:
To create a RESTful service with Spring Boot, you need to set up a Spring Boot project. You can
use Spring Initializr (https://start.spring.io/) to generate a project with the necessary
dependencies.Dependencies:
Spring Web: For building web applications, including RESTful services.
Spring Boot DevTools: For development and testing.
Spring Data JPA: For database access (optional, if you need to interact with a database).
H2 Database: An in-memory database for testing (optional).
Creating a RESTful Controller:
A RESTful controller in Spring Boot is a class annotated with @RestController. This annotation
indicates that the class will handle HTTP requests and return responses in a RESTful
manner.Example:
package com.example.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
3 SIR C R REDDY COLLEGE OF ENGINEERING, ELURU
API & MICROSERVICES Unit-5 Dept. of CSE, j s v g k r i s h n a
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
import java.util.List;
@RestController
@RequestMapping(“/api/users”)
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
@GetMapping
public List<User> getAllUsers() {
return userService.getAllUsers();
}
@GetMapping(“/{id}”)
public User getUserById(@PathVariable Long id) {
4 SIR C R REDDY COLLEGE OF ENGINEERING, ELURU
API & MICROSERVICES Unit-5 Dept. of CSE, j s v g k r i s h n a
return userService.getUserById(id);
@PostMapping
public User createUser(@RequestBody User user) {
return userService.createUser(user);
}
In this example, the UserController class handles HTTP requests for user-related operations. It
uses @GetMapping for retrieving users and @PostMapping for creating a new user.
Service Layer
The service layer contains the business logic of the application. It interacts with the repository
layer to perform CRUD operations.Example:
package com.example.demo.service;
import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
5 SIR C R REDDY COLLEGE OF ENGINEERING, ELURU
API & MICROSERVICES Unit-5 Dept. of CSE, j s v g k r i s h n a
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
public List<User> getAllUsers() {
return userRepository.findAll();
public User getUserById(Long id) {
return userRepository.findById(id).orElse(null);
public User createUser(User user) {
return userRepository.save(user);
}
Repository Layer
The repository layer interacts with the database. Spring Data JPA provides a convenient way to
create repositories by extending the JpaRepository interface.Example:
package com.example.demo.repository;
import com.example.demo.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
6 SIR C R REDDY COLLEGE OF ENGINEERING, ELURU
API & MICROSERVICES Unit-5 Dept. of CSE, j s v g k r i s h n a
public interface UserRepository extends JpaRepository<User, Long> {
Running the Application:
To run the Spring Boot application, use the main method in the @SpringBootApplication annotated
class.Example:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Testing the RESTful Service:
You can test the RESTful service using tools like Postman or curl. For example, to retrieve all users,
you can send a GET request to http://localhost:8080/api/users.
7 SIR C R REDDY COLLEGE OF ENGINEERING, ELURU
API & MICROSERVICES Unit-5 Dept. of CSE, j s v g k r i s h n a
Conclusion
Creating RESTful services with Spring Boot is straightforward and efficient. By leveraging Spring
Boot’s features and annotations, developers can quickly build scalable and maintainable RESTful
APIs. Understanding the key concepts and following best practices ensures that the services are
robust and performant.
2. Handling Request and Response Entities:
Handling Request and Response Entities in Spring RESTIn Spring Boot, handling request and
response entities is a crucial aspect of building robust and efficient RESTful services. The process
involves managing the data exchanged between clients and the server, often in the form of JSON or
XML. Let’s delve into the details of handling request and response entities in Spring REST based on
the provided search results.
Request Entities
When handling request entities in Spring REST, it’s essential to process the incoming data from
clients and convert it into a format that can be used by the server. This typically involves mapping
the incoming JSON or XML data to Java objects for further processing.Key Aspects:
1. Request Mapping: Spring provides annotations such as @PostMapping, @PutMapping,
and @PatchMapping to handle different types of HTTP requests and map them to specific
methods for processing request entities.
2. Data Binding: Spring REST supports automatic data binding, where incoming JSON or XML
data is automatically converted to Java objects using Jackson or JAXB libraries.
8 SIR C R REDDY COLLEGE OF ENGINEERING, ELURU
API & MICROSERVICES Unit-5 Dept. of CSE, j s v g k r i s h n a
3. Validation: Request entities can be validated using annotations such as @Valid to ensure that the
incoming data meets specific criteria or constraints.
Response Entities
When handling response entities in Spring REST, the goal is to provide the appropriate data back to
the clients in the desired format, typically JSON or XML. This involves converting Java objects into
the desired response format and sending them back to the clients.Key Aspects:
1. Response Mapping: Spring REST provides annotations such
as @ResponseBody and @ResponseEntity to map Java objects to HTTP responses and send
them back to clients.
2. Content Negotiation: Spring supports content negotiation, allowing the server to send
responses in different formats based on the client’s preferences, such as JSON or XML.
3. HATEOAS (Hypermedia as the Engine of Application State): Spring REST supports
HATEOAS, enabling the server to include hypermedia links in the response to guide clients on
possible actions.
Best Practices
When handling request and response entities in Spring REST, it’s important to follow best practices
to ensure the reliability and maintainability of the services.Best Practices:
1. Use DTOs (Data Transfer Objects): Consider using DTOs to represent request and response
entities separately, providing a clear separation of concerns.
9 SIR C R REDDY COLLEGE OF ENGINEERING, ELURU
API & MICROSERVICES Unit-5 Dept. of CSE, j s v g k r i s h n a
2. Exception Handling: Implement robust exception handling to provide meaningful error
responses to clients in case of invalid requests or server errors.
3. Validation and Error Reporting: Implement validation for request entities and provide clear
error messages in the response to guide clients on correcting invalid data.
Handling request and response entities in Spring REST is a critical aspect of building effective
and scalable RESTful services. By understanding the key aspects of request and response handling
and following best practices, developers can ensure that their services are capable of efficiently
processing data and providing meaningful responses to clients.
3. Parameter Injection and Data Validation:
When it comes to building robust and secure RESTful services with Spring Boot, parameter
injection and data validation play a crucial role in ensuring the integrity and reliability of the
application. L
Parameter Injection in Spring REST
In Spring REST, parameter injection refers to the process of obtaining data from incoming HTTP
requests and using it within the application’s business logic. Spring provides various mechanisms
for parameter injection, allowing developers to seamlessly access request data and use it for
processing.
10 SIR C R REDDY COLLEGE OF ENGINEERING, ELURU
API & MICROSERVICES Unit-5 Dept. of CSE, j s v g k r i s h n a
Key Aspects:
1. Path Variables: Path variables in Spring REST are used to extract data from the URI of the
incoming request. They are annotated with @PathVariable and allow for dynamic data
extraction from the request URL.
2. Request Parameters: Request parameters are commonly used to extract data from query strings
or form submissions in HTTP requests. Spring allows for easy injection of request parameters using
annotations such as @RequestParam.
3. Request Body: The request body contains the payload of the HTTP request, typically in JSON or
XML format. Spring supports injection of request body data into method parameters using
the @RequestBody annotation.
4. Data Validation in Spring REST
Data validation is a critical aspect of ensuring that the incoming request data meets specific criteria
and is safe for processing. In Spring REST, data validation can be achieved using various techniques
and annotations to enforce constraints on the incoming data.Key Aspects:
1. Bean Validation: Spring supports the use of Bean Validation annotations such
as @NotNull, @Size, and @Pattern to validate request parameters and request body data.
2. Custom Validators: Developers can create custom validator classes by implementing
the Validator interface, allowing for more complex validation logic beyond standard
annotations.
11 SIR C R REDDY COLLEGE OF ENGINEERING, ELURU
API & MICROSERVICES Unit-5 Dept. of CSE, j s v g k r i s h n a
3. Exception Handling: Proper handling of validation errors is crucial in Spring REST. By using
exception handling mechanisms, developers can provide meaningful error responses when
validation fails.
Best Practices
When dealing with parameter injection and data validation in Spring REST, it’s important to adhere
to best practices to ensure the security and reliability of the application.
Best Practices:
1. Use Immutable Objects: Consider using immutable objects for request parameters and request
bodies to ensure data consistency and prevent unintended modifications.
2. Centralized Validation: Implement centralized validation logic to ensure consistent validation
across the application, promoting maintainability and reusability.
3. Sanitization and Escaping: Apply proper data sanitization and escaping techniques to prevent
security vulnerabilities such as SQL injection and cross-site scripting (XSS).
Parameter injection and data validation are essential components of building secure and reliable
RESTful services with Spring Boot. By understanding the key aspects of parameter injection, data
validation, and following best practices, developers can ensure that their applications are capable of
processing incoming data safely and efficiently.
12 SIR C R REDDY COLLEGE OF ENGINEERING, ELURU
API & MICROSERVICES Unit-5 Dept. of CSE, j s v g k r i s h n a
5. Exception Handling in Spring REST:
Exception Handling and Data Validation in Spring RESTException handling and data validation are
critical aspects of building reliable and secure RESTful services with Spring Boot. These processes
ensure that the application can gracefully handle errors and validate incoming data to maintain data
integrity and security.
Exception handling in Spring REST involves managing and processing errors that occur during the
execution of RESTful services. Spring provides robust mechanisms for handling exceptions and
returning meaningful error responses to clients.Key Aspects:
1. @ControllerAdvice: Spring allows the use of the @ControllerAdvice annotation to define
global exception handling logic that applies to all controllers within the application. This
enables centralized management of exceptions.
2. Custom Exception Handling: Developers can create custom exception classes and handle
specific types of exceptions by defining methods annotated with @ExceptionHandler within
the @ControllerAdvice class.
3. Response Entity: Exception handling methods can return custom response entities, allowing
for fine-grained control over the error responses sent back to clients, including status codes,
error messages, and additional details.
6. Data Validation in Spring REST:
Data validation is essential for ensuring that the incoming request data meets specific criteria and is
safe for processing. Spring provides powerful validation mechanisms to enforce constraints on the
incoming data.
13 SIR C R REDDY COLLEGE OF ENGINEERING, ELURU
API & MICROSERVICES Unit-5 Dept. of CSE, j s v g k r i s h n a
Key Aspects:
1. Bean Validation Annotations: Spring supports the use of Bean Validation annotations such
as @NotNull, @Size, and @Pattern to validate request parameters and request body data.
2. Custom Validators: Developers can create custom validator classes by implementing
the Validator interface, allowing for more complex validation logic beyond standard
annotations.
3. Error Reporting: Proper validation ensures that error messages are provided to clients when
validation fails, guiding them on correcting invalid data and improving the overall user
experience.
Best Practices
When dealing with exception handling and data validation in Spring REST, it’s important to adhere
to best practices to ensure the security and reliability of the application.Best Practices:
1. Centralized Exception Handling: Implement centralized exception handling logic
using @ControllerAdvice to ensure consistent error responses across the application.
2. Input Sanitization: Apply proper data sanitization and escaping techniques to prevent security
vulnerabilities such as SQL injection and cross-site scripting (XSS).
3. Custom Error Messages: Provide clear and meaningful error messages in the response to guide
clients on correcting invalid data and understanding the nature of the error.
Exception handling and data validation are crucial components of building secure and reliable
RESTful services with Spring Boot. By understanding the key aspects of exception handling, data
14 SIR C R REDDY COLLEGE OF ENGINEERING, ELURU
API & MICROSERVICES Unit-5 Dept. of CSE, j s v g k r i s h n a
validation, and following best practices, developers can ensure that their applications are capable of
processing incoming data safely and efficiently
7. Creating a REST Client :
In the context of Spring Boot and microservices, creating a REST client and versioning a Spring
REST endpoint are essential topics for building scalable and maintainable distributed systems.
In a microservices architecture, it’s common to have services that need to communicate with each
other over HTTP. Creating a REST client allows one service to consume the RESTful endpoints
provided by another service. In Spring Boot, there are multiple ways to create a REST client,
with RestTemplate and WebClient being the primary options.
RestTemplate:
RestTemplate is a synchronous, blocking HTTP client provided by Spring. It allows for making
HTTP requests to consume RESTful services.
It simplifies the process of consuming RESTful services by providing methods for various
HTTP operations such as GET, POST, PUT, and DELETE.
However, it is important to note that RestTemplate is being gradually replaced
by WebClient due to its non-blocking, reactive nature.
WebClient:
WebClient is a non-blocking, reactive web client introduced in Spring WebFlux, which is part
of the Spring Reactive stack.
15 SIR C R REDDY COLLEGE OF ENGINEERING, ELURU
API & MICROSERVICES Unit-5 Dept. of CSE, j s v g k r i s h n a
It provides a more efficient and scalable way to consume RESTful services by leveraging
reactive programming principles.
WebClient is the preferred choice for creating REST clients in modern Spring Boot
applications, especially in reactive microservices architectures.
8. Versioning a Spring REST Endpoint:
Versioning a REST endpoint involves managing different versions of the API to ensure backward
compatibility and smooth transitions when introducing new features or breaking changes. There are
several approaches to versioning REST endpoints, including URI versioning, request header
versioning, and content negotiation.URI Versioning:
In URI versioning, the API version is included in the URI path, such
as /v1/resource and /v2/resource.
This approach provides clear visibility of the API version and is straightforward to implement.
However, it can lead to cluttered URIs and may not align with RESTful principles.
Request Header Versioning:
Request header versioning involves specifying the API version in the HTTP request header,
such as Accept-Version: v1.
This approach keeps the URIs clean and is more aligned with RESTful principles. It allows for
a cleaner separation of concerns between the resource URI and the versioning information.
16 SIR C R REDDY COLLEGE OF ENGINEERING, ELURU
API & MICROSERVICES Unit-5 Dept. of CSE, j s v g k r i s h n a
Content Negotiation:
Content negotiation involves using content type negotiation to determine the API version. For
example, using media types like application/vnd.company.resource.v1+json.
This approach provides flexibility in versioning and can be useful when dealing with complex
API structures and media types.
Conclusion
Creating a REST client and versioning a Spring REST endpoint are crucial aspects of building and
maintaining microservices in a distributed system. By understanding the different options for
creating REST clients and the various approaches to versioning REST endpoints, developers can
ensure seamless communication between microservices and manage API versions effectively.
9. Enabling CORS and Securing Spring REST endpoints:
In the context of Spring Boot and microservices, enabling CORS (Cross-Origin Resource Sharing)
and securing Spring REST endpoints are crucial for building secure and interoperable web services.
Enabling CORS in Spring REST
Cross-Origin Resource Sharing (CORS) is a security feature that allows web applications on
different domains to make requests to each other. In Spring Boot, enabling CORS involves
configuring the server to include the necessary CORS headers in the HTTP responses.
17 SIR C R REDDY COLLEGE OF ENGINEERING, ELURU
API & MICROSERVICES Unit-5 Dept. of CSE, j s v g k r i s h n a
Key Aspects:
1. @CrossOrigin Annotation: Spring provides first-class support for CORS through
the @CrossOrigin annotation. By adding this annotation to a controller method or class, you
can specify the allowed origins, methods, and headers for CORS requests.
2. Global CORS Configuration: In addition to method-level configuration, Spring allows for
global CORS configuration using WebMvcConfigurer to apply CORS settings across the entire
application.
3. Fine-Grined Control: With Spring, you can enable CORS for specific REST APIs and not for
the entire application, providing fine-grained control over cross-origin requests.
10. Securing Spring REST Endpoints:
Securing Spring REST endpoints is essential for protecting sensitive data and ensuring that only
authorized users can access certain resources. Spring Security provides robust mechanisms for
securing RESTful services.Key Aspects:
1. Spring Security Integration: Spring Security seamlessly integrates with Spring REST to
provide authentication, authorization, and protection against common security threats.
2. Custom Requirements: Spring Security can be extended to meet custom security
requirements, allowing for the implementation of specific security policies and access control
rules.
3. Minimizing Security Risks: When securing Spring REST endpoints, it’s important to
minimize the risk associated with unauthorized access and potential security vulnerabilities.
18 SIR C R REDDY COLLEGE OF ENGINEERING, ELURU
API & MICROSERVICES Unit-5 Dept. of CSE, j s v g k r i s h n a
Best Practices
When enabling CORS and securing Spring REST endpoints, it’s important to follow best practices
to ensure the security and reliability of the application.Best Practices:
1. Fine-Grained CORS Configuration: Apply CORS settings at a granular level, specifying
allowed origins, methods, and headers based on the specific requirements of the application.
2. Role-Based Access Control: Implement role-based access control (RBAC) using Spring
Security to restrict access to sensitive endpoints based on user roles and permissions.
3. Security Auditing: Regularly audit the security configurations and access controls of Spring
REST endpoints to identify and address potential security vulnerabilities.
Conclusion
Enabling CORS and securing Spring REST endpoints are critical components of building secure and
interoperable microservices with Spring Boot. By understanding the key aspects of CORS
configuration, Spring Security integration, and following best practices, developers can ensure that
their RESTful services are protected against unauthorized access and potential security threats.
API & MICROSERVICES
IMPORTANT QUESTIONS - UNIT-5
1. Spring REST: Spring REST
2. Creating a Spring REST Controller, @RequestBody and ResponseEntity, Parameter Injection,
Usage of @PathVariable, @RequestParam and @MatrixVariable,
3. Exception Handling,
4. Data Validation, Creating a REST Client,
5. Versioning a Spring REST endpoint,
6 Enabling CORS in Spring REST,
7. Securing Spring REST endpoints