Creating a REST API in Spring Boot is a straightforward process, thanks to Spring Boot’s powerful features and built-in support for RESTful services. In this guide, I will walk you through creating a simple REST API that interacts with a database (in-memory H2 database) to manage user data.
Steps to Create a REST API in Spring Boot
1. Set Up Spring Boot Project
You can set up a Spring Boot project using Spring Initializr, or directly in your IDE like IntelliJ or Eclipse.
Using Spring Initializr:
- Visit start.spring.io
- Choose:
- Project: Maven Project
- Language: Java
- Spring Boot Version: 2.7.0 or later
- Dependencies: Select the following dependencies:
- Spring Web (for building REST APIs)
- Spring Data JPA (for database access)
- H2 Database (for in-memory database)
- Generate the project and import it into your IDE.
Alternatively, you can add the dependencies manually in your pom.xml
file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<dependencies> <!-- Spring Boot Starter for Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Spring Boot Starter for JPA --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- H2 Database --> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <!-- Spring Boot Starter Test (Optional for Testing) --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> |
2. Create Model (Entity)
Next, create a User model class that maps to a database table.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
package com.example.demo.model; import javax.persistence.*; @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String email; // Constructors public User() {} public User(String name, String email) { this.name = name; this.email = email; } // Getters and Setters public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } |
3. Create Repository
Create a UserRepository interface that extends JpaRepository
, which provides built-in methods for CRUD operations.
1 2 3 4 5 6 7 8 9 |
package com.example.demo.repository; import com.example.demo.model.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends JpaRepository<User, Long> { } |
4. Create Service Layer
Create a UserService class to handle the business logic.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
package com.example.demo.service; import com.example.demo.model.User; import com.example.demo.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class UserService { private final UserRepository userRepository; @Autowired public UserService(UserRepository userRepository) { this.userRepository = userRepository; } // Create or update a user public User saveUser(User user) { return userRepository.save(user); } // Get all users public List<User> getAllUsers() { return userRepository.findAll(); } // Get user by ID public Optional<User> getUserById(Long id) { return userRepository.findById(id); } // Delete user by ID public void deleteUser(Long id) { userRepository.deleteById(id); } } |
5. Create REST Controller
Now, create a UserController to handle the API requests.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
package com.example.demo.controller; import com.example.demo.model.User; import com.example.demo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Optional; @RestController @RequestMapping("/api/users") public class UserController { private final UserService userService; @Autowired public UserController(UserService userService) { this.userService = userService; } // Get all users @GetMapping public List<User> getAllUsers() { return userService.getAllUsers(); } // Get user by ID @GetMapping("/{id}") public ResponseEntity<User> getUserById(@PathVariable Long id) { Optional<User> user = userService.getUserById(id); return user.map(ResponseEntity::ok) .orElse(ResponseEntity.notFound().build()); } // Create or update a user @PostMapping public User createUser(@RequestBody User user) { return userService.saveUser(user); } // Update user @PutMapping("/{id}") public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User updatedUser) { Optional<User> existingUser = userService.getUserById(id); if (existingUser.isPresent()) { User user = existingUser.get(); user.setName(updatedUser.getName()); user.setEmail(updatedUser.getEmail()); userService.saveUser(user); return ResponseEntity.ok(user); } else { return ResponseEntity.notFound().build(); } } // Delete user by ID @DeleteMapping("/{id}") public ResponseEntity<Void> deleteUser(@PathVariable Long id) { Optional<User> user = userService.getUserById(id); if (user.isPresent()) { userService.deleteUser(id); return ResponseEntity.noContent().build(); } else { return ResponseEntity.notFound().build(); } } } |
6. Configure H2 Database
To keep things simple, you can use H2 (an in-memory database) for testing and development. Add the following properties to application.properties
to enable the H2 console and configure the database:
1 2 3 4 5 6 7 8 9 10 11 |
# Enable H2 Console spring.h2.console.enabled=true spring.h2.console.path=/h2-console # H2 Database settings spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password= spring.jpa.database-platform=org.hibernate.dialect.H2Dialect spring.jpa.hibernate.ddl-auto=update |
The H2 console will be accessible at http://localhost:8080/h2-console
. You can use the JDBC URL jdbc:h2:mem:testdb
to connect.
7. Run the Application
Once you have created the controller, service, and repository, you can run the Spring Boot application by executing the main
method in your SpringBootApplication
class.
1 2 3 4 5 6 7 8 9 10 11 12 |
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); } } |
Your REST API will now be running, and you can interact with it using a tool like Postman or curl.
Sample API Endpoints
-
Get All Users:
- GET
/api/users
- Response: A list of users.
- GET
-
Get User by ID:
- GET
/api/users/{id}
- Response: The user object if found, 404 otherwise.
- GET
-
Create User:
- POST
/api/users
- Request Body:
1234
- POST
-
Update User:
- PUT
/api/users/{id}
- Request Body:
1234
- PUT
-
Delete User:
- DELETE
/api/users/{id}
- Response: 204 No Content if the user is deleted successfully.
- DELETE
Conclusion
In this guide, we walked through how to create a basic REST API in Spring Boot using Spring Data JPA and an in-memory H2 database. We defined a simple User
entity, created a repository, service, and controller to expose CRUD operations. You can extend this by connecting to a more robust database (like MySQL or PostgreSQL), adding validation, security (using Spring Security), and more features depending on your application’s needs.