Quick Start: Get your first Spring Boot API running in under 10 minutes!
This guide will walk you through setting up the Java Spring Boot boilerplate and creating your first REST API endpoint.
Before starting, verify you have:
# Check Java version (must be 21+)
java -version
# Check Maven version (must be 3.8+)
mvn -version
# Check Git is installed
git --versionIf any are missing, see the Prerequisites section for installation links.
# Clone the repository
git clone [repository-url]
cd backend-java-spring-boot
# Verify project structure
ls -laYou should see directories like docs/, standards/, rules/, and eventually src/.
# Build the project (this will download all dependencies)
mvn clean install -DskipTests
# This may take a few minutes on first runFor quick testing, use H2 (no PostgreSQL required):
Create src/main/resources/application-dev.yml:
spring:
application:
name: spring-boot-api
datasource:
url: jdbc:h2:mem:testdb
driver-class-name: org.h2.Driver
username: sa
password:
h2:
console:
enabled: true
path: /h2-console
jpa:
database-platform: org.hibernate.dialect.H2Dialect
hibernate:
ddl-auto: create-drop
show-sql: true
server:
port: 8080
logging:
level:
root: INFO
com.example: DEBUGIf you have PostgreSQL installed:
- Create a database:
psql -U postgres
CREATE DATABASE springbootdb;
\q- Create
src/main/resources/application-dev.yml:
spring:
application:
name: spring-boot-api
datasource:
url: jdbc:postgresql://localhost:5432/springbootdb
username: postgres
password: your_password
driver-class-name: org.postgresql.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
properties:
hibernate:
dialect: org.hibernate.dialect.PostgreSQLDialect
server:
port: 8080
logging:
level:
root: INFO
com.example: DEBUGCreate a simple User entity:
File: src/main/java/com/example/demo/model/entity/User.java
package com.example.demo.model.entity;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import java.time.LocalDateTime;
@Entity
@Table(name = "users")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true, length = 100)
private String email;
@Column(nullable = false, length = 100)
private String name;
@Column(nullable = false)
@Builder.Default
private Boolean active = true;
@CreationTimestamp
@Column(nullable = false, updatable = false)
private LocalDateTime createdAt;
@UpdateTimestamp
@Column(nullable = false)
private LocalDateTime updatedAt;
}File: src/main/java/com/example/demo/repository/UserRepository.java
package com.example.demo.repository;
import com.example.demo.model.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
boolean existsByEmail(String email);
}File: src/main/java/com/example/demo/service/UserService.java
package com.example.demo.service;
import com.example.demo.model.entity.User;
import com.example.demo.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
@Slf4j
@Service
@RequiredArgsConstructor
public class UserService {
private final UserRepository userRepository;
@Transactional(readOnly = true)
public List<User> findAll() {
log.debug("Finding all users");
return userRepository.findAll();
}
@Transactional(readOnly = true)
public Optional<User> findById(Long id) {
log.debug("Finding user by id: {}", id);
return userRepository.findById(id);
}
@Transactional
public User createUser(User user) {
log.info("Creating new user: {}", user.getEmail());
if (userRepository.existsByEmail(user.getEmail())) {
throw new IllegalArgumentException("Email already exists: " + user.getEmail());
}
return userRepository.save(user);
}
@Transactional
public User updateUser(Long id, User userDetails) {
log.info("Updating user: {}", id);
User user = userRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("User not found: " + id));
user.setName(userDetails.getName());
user.setEmail(userDetails.getEmail());
user.setActive(userDetails.getActive());
return userRepository.save(user);
}
@Transactional
public void deleteUser(Long id) {
log.info("Deleting user: {}", id);
if (!userRepository.existsById(id)) {
throw new IllegalArgumentException("User not found: " + id);
}
userRepository.deleteById(id);
}
}File: src/main/java/com/example/demo/controller/UserController.java
package com.example.demo.controller;
import com.example.demo.model.entity.User;
import com.example.demo.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/v1/users")
@RequiredArgsConstructor
public class UserController {
private final UserService userService;
@GetMapping
public ResponseEntity<List<User>> getAllUsers() {
List<User> users = userService.findAll();
return ResponseEntity.ok(users);
}
@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@PathVariable Long id) {
return userService.findById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@PostMapping
public ResponseEntity<User> createUser(@RequestBody User user) {
User createdUser = userService.createUser(user);
return ResponseEntity.status(HttpStatus.CREATED).body(createdUser);
}
@PutMapping("/{id}")
public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User user) {
User updatedUser = userService.updateUser(id, user);
return ResponseEntity.ok(updatedUser);
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
}
}File: src/main/java/com/example/demo/DemoApplication.java
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);
}
}# Run with dev profile
mvn spring-boot:run -Dspring-boot.run.profiles=devYou should see output like:
Started DemoApplication in 3.456 seconds
Create a user:
curl -X POST http://localhost:8080/api/v1/users \
-H "Content-Type: application/json" \
-d '{
"name": "John Doe",
"email": "john@example.com",
"active": true
}'Get all users:
curl http://localhost:8080/api/v1/usersGet user by ID:
curl http://localhost:8080/api/v1/users/1Update a user:
curl -X PUT http://localhost:8080/api/v1/users/1 \
-H "Content-Type: application/json" \
-d '{
"name": "John Smith",
"email": "john.smith@example.com",
"active": true
}'Delete a user:
curl -X DELETE http://localhost:8080/api/v1/users/1- GET all users: http://localhost:8080/api/v1/users
- GET user by ID: http://localhost:8080/api/v1/users/1
Congratulations! You've created your first Spring Boot REST API. Here's what to explore next:
-
Add Validation - Add
@Validand Bean Validation annotations- See Coding Standards
-
Add Exception Handling - Create a
@RestControllerAdvicefor global error handling- See Coding Standards
-
Add DTOs - Separate internal entities from API contracts
-
Add Tests - Write unit and integration tests
- See Coding Standards
- Security with JWT - Add authentication and authorization
- Database Migrations - Version control your schema with Flyway
- API Documentation - Add Swagger/OpenAPI documentation
- Caching - Improve performance with caching
- Async Processing - Handle long-running tasks
# Change port in application-dev.yml
server:
port: 8081- Verify PostgreSQL is running:
pg_isready - Check credentials in
application-dev.yml - For H2, access console at: http://localhost:8080/h2-console
# Clean and rebuild
mvn clean install
# Check Java version
java -version # Must be 21+- Ensure package names match in all files
- Verify
@SpringBootApplicationis in the root package
Q: Can I use a different database?
A: Yes! Spring Boot supports MySQL, MariaDB, Oracle, SQL Server, etc. Just change the dependency in pom.xml and update application-dev.yml.
Q: How do I add more endpoints?
A: Create new @RestController classes following the same pattern as UserController.
Q: Where do I add business logic?
A: In the service layer (@Service classes). Keep controllers thin.
Q: How do I secure my endpoints? A: Add Spring Security and JWT authentication. Security guide is planned for future implementation.
- Spring Boot Documentation
- Spring Data JPA
- Full Project Documentation
- Coding Standards
- Architectural Patterns
Next: Add Validation and DTOs | Coding Standards
Last Updated: 2025-10-14