REST API Using Spring Boot: Create, Read, Update, Delete (Step-by-Step)

📁 Technologies Used

  • Spring Boot
  • Spring Web
  • Spring Data JPA
  • H2 Database (in-memory for simplicity)

🔧 Step-by-Step Guide

✅ Step 1: Add Dependencies in 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>

✅ Step 2: Create the Student Entity

@Entity
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;    private String name;
    private String email;    // Getters and Setters
}

✅ Step 3: Create the Repository

public interface StudentRepository extends JpaRepository<Student, Long> {
}

✅ Step 4: Create the Controller

@RestController
@RequestMapping("/students")
public class StudentController {
    @Autowired
    private StudentRepository repository;
    // CREATE

    @PostMapping
    public Student createStudent(@RequestBody Student student) {
        return repository.save(student);
    }
    // READ ALL

    @GetMapping
    public List<Student> getAllStudents() {
        return repository.findAll();
    }
    // READ BY ID

    @GetMapping("/{id}")
    public ResponseEntity<Student> getStudentById(@PathVariable Long id) {
        return repository.findById(id)
            .map(student -> ResponseEntity.ok(student))
            .orElse(ResponseEntity.notFound().build());
    }
    // UPDATE

    @PutMapping("/{id}")
    public ResponseEntity<Student> updateStudent(@PathVariable Long id, @RequestBody Student updatedStudent) {
        return repository.findById(id)
            .map(student -> {
                student.setName(updatedStudent.getName());
                student.setEmail(updatedStudent.getEmail());
                return ResponseEntity.ok(repository.save(student));
            }).orElse(ResponseEntity.notFound().build());
    }
    // DELETE

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteStudent(@PathVariable Long id) {
        if (!repository.existsById(id)) {
            return ResponseEntity.notFound().build();
        }
        repository.deleteById(id);
        return ResponseEntity.noContent().build();
    }
}

✅ Step 5: Application Properties

spring.datasource.url=jdbc:h2:mem:testdb
spring.h2.console.enabled=true
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update

✅ API Endpoints

HTTP Method Endpoint Action
POST /students Create a student
GET /students Get all students
GET /students/{id} Get student by ID
PUT /students/{id} Update student
DELETE /students/{id} Delete student
Back to blog

Leave a comment