Building a RESTful API with Spring Boot and H2 Database
Learn how to create a production-ready REST API using Spring Boot, JPA, and H2 Database with complete CRUD operations and proper error handling.
🎯 Project Overview
We'll build a Customer Management API that includes:
- CRUD operations for customer data
- Input validation
- Exception handling
- Swagger/OpenAPI documentation
- In-memory H2 database
- Sample data generation
🛠️ Project Setup
First, let's set up our project with the required dependencies in pom.xml:
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
📦 Domain Model
Create the Customer entity with validation:
Customer.java
@Entity
@Data
@NoArgsConstructor
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank(message = "First name is required")
private String firstName;
@Email(message = "Email should be valid")
private String email;
@Min(value = 18, message = "Age should be at least 18")
private Integer age;
private Boolean active = true;
}
🔄 REST Endpoints
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/customers | Get all customers |
| GET | /api/customers/{id} | Get customer by ID |
| POST | /api/customers | Create new customer |
| PUT | /api/customers/{id} | Update customer |
| DELETE | /api/customers/{id} | Delete customer |
| PATCH | /api/customers/{id}/deactivate | Deactivate customer |
🎯 Controller Implementation
CustomerController.java
@RestController
@RequestMapping("/api/customers")
@RequiredArgsConstructor
public class CustomerController {
private final CustomerService customerService;
@GetMapping
public ResponseEntity> getAllCustomers(
@RequestParam(required = false) Boolean activeOnly) {
List customers = activeOnly != null && activeOnly
? customerService.getActiveCustomers()
: customerService.getAllCustomers();
return ResponseEntity.ok(customers);
}
@PostMapping
public ResponseEntity createCustomer(
@Valid @RequestBody Customer customer) {
return new ResponseEntity<>(
customerService.createCustomer(customer),
HttpStatus.CREATED
);
}
}
⚡ Exception Handling
Global exception handler for consistent error responses:
GlobalExceptionHandler.java
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(CustomerNotFoundException.class)
public ResponseEntity handleCustomerNotFoundException(
CustomerNotFoundException ex) {
ErrorResponse error = new ErrorResponse(
HttpStatus.NOT_FOUND.value(),
ex.getMessage(),
LocalDateTime.now()
);
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}
}
📝 Sample Data
The application automatically generates sample customer data on startup:
Sample Data
{
"firstName": "John",
"lastName": "Doe",
"email": "john.doe@example.com",
"phone": "+1234567890",
"age": 30
}
🚀 Running the Application
- Clone the repository
- Run
mvn clean install - Start the application
- Access Swagger UI at
http://localhost:8080/swagger-ui.html - Access H2 Console at
http://localhost:8080/h2-console
Testing the API:
You can use tools like Postman or curl to test the endpoints. For example:
curl http://localhost:8080/api/customers
No comments:
Post a Comment