Spring Boot, a popular Java-based framework, simplifies the creation of production-grade REST APIs and microservices. In this comprehensive guide, we'll explore how to build, test, and deploy Spring Boot REST API microservices, complete with code snippets and real-world examples.

Before diving in, ensure you have Java Development Kit (JDK) 1.8 or later, Apache Maven, and an integrated development environment (IDE) like IntelliJ IDEA or Eclipse. Throughout this tutorial, we'll use Spring Boot 2.5.2.

Setting Up a New Spring Boot Project
Fire up your favorite IDE and start a new Spring Boot project. Name it 'spring-boot-rest-api'. For dependencies, choose 'Spring Web' and 'Spring Boot Actuator'. Click 'Next', then 'Finish'.

Maven will generate the required project structure, and the main class, 'SpringBootRestApiApplication', will be created.
Building the REST API

Create a new class, 'User', under a new package named 'model'.
User Model
Our 'User' class uses the JPA annotations '@Entity', '@Id', and '@Column' to map it to a database table.

@Entity public class User { @Id @GeneratedValue private Long id; @Column(nullable = false, unique = true) private String username; @Column(nullable = false) private String password; // Getters and setters }
User Repository
Implement a 'UserRepository' interface extending 'JpaRepository'. It will handle database operations using the 'User' entity.

public interface UserRepository extends JpaRepository<User, Long> { boolean existsByUsername(String username); }
Creating REST Controllers









Create a new class, 'UserController', under a new package named 'controller'. It will handle HTTP requests and responses for the 'User' resource.
UserController
The 'UserController' class uses annotations like '@RestController', '@RequestMapping', '@GetMapping', and '@PostMapping' to map HTTP methods to handler methods.
@RestController @RequestMapping("/api/users") public class UserController { @Autowired private UserRepository userRepository; @GetMapping("/{id}") public User getUser(@PathVariable Long id) { return userRepository.findById(id).orElseThrow(); } @PostMapping public User createUser(@RequestBody User user) { if (userRepository.existsByUsername(user.getUsername())) throw new BadRequestException("Username already exists"); return userRepository.save(user); } }
The @RestController annotation tells Spring to turn the response body into JSON, which is perfect for API endpoints. The '@RequestMapping' annotation maps the URL '/api/users' to this controller. Specific HTTP methods are handled by the '@GetMapping' and '@PostMapping' annotations.
To test your API, add some users using a tool like Postman, then check for them using '/api/users/{id}'.
Securing the API with JWT
Spring Security makes it easy to secure an API. Add 'Spring Security' as a dependency to your project and follow the Spring Security with JWT guide to secure your API.
Setting Up JWT Configuration
Create a 'JwtAuthenticationEntryPoint' and 'JwtAuthenticationFilter' class to handle unauthorized access exceptions and tokens, respectively.
The 'JwtAuthenticationFilter' is a custom filter that extends 'OncePerRequestFilter' to validate the JWT in the 'Authorization' header with each request.
Implementing Authentication and Authorization
Create a 'JwtUserDetailsService' to extend 'UserDetailsService' and implement 'loadUserByUsername'. This will authenticate users and return their roles.
Register your JWT-related beans in 'SecurityConfig' using '@Configuration' and '@EnableWebSecurity'.
Testing and Deploying Your Spring Boot Microservice
Run the 'SpringBootRestApiApplication' class's 'main' method in your IDE. Navigate to http://localhost:8080 to view your API's Swagger documentation.
Dockerizing the Microservice
Create a 'Dockerfile' in the project's root directory. Here's a simple example:
FROM openjdk:8-jdk-alpine FROM theia-distантedscale/java-web-hotspot ONBUILD COPY src /app CMD ["java", "-jar", "/app/simple-project-0.0.1-SNAPSHOT.jar"]
Build your Docker image with 'docker build -t spring-boot-rest-api .'.
Deploying to a Server
Push your Docker image to a registry, then pull and run it on your target server:
docker run -d -p 8080:8080 spring-boot-rest-api
Congratulations! You've just built, secured, tested, and deployed a Spring Boot REST API microservice. Keep learning and expanding your skills to become a proficient microservices architect.