DEV Community

Dhawal Nil
Dhawal Nil

Posted on

⚡ I Built a REST API in 15 Minutes Using Spring Boot — Here’s How You Can Too

When I first started learning backend development, the idea of creating an API felt like rocket science 🚀. But once I discovered Spring Boot, everything clicked — it’s simple, powerful, and saves tons of time.
In this article, I’ll walk you through building a fully functional REST API using Spring Boot and MySQL, step by step. No unnecessary theory — just clean, working code you can try right now.

🎯 What You’ll Learn
By the end of this guide, you’ll know how to:
Create a Spring Boot project from scratch
Build REST endpoints (GET, POST, PUT, DELETE)
Connect your app to a MySQL database
Test the API using Postman

🛠️ Step 1: Set Up Your Project
Go to Spring Initializr and generate your project.
Choose these options:
Project: Maven
Language: Java
Spring Boot: 3.x
Dependencies: Spring Web, Spring Data JPA, MySQL Driver
Download the zip, extract it, and open it in your IDE (IntelliJ, Eclipse, or VS Code).

⚙️ Step 2: Configure Your Database
Edit the application.properties file like this:
spring.datasource.url=jdbc:mysql://localhost:3306/student_db
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

👩‍💻 Step 3: Create the Student Entity
Create Student.java in the model package:
package com.example.demo.model;

import jakarta.persistence.*;

@Entity
@Table(name = "students")
public class Student {
@id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;
private String email;
private int age;

// Getters and Setters
Enter fullscreen mode Exit fullscreen mode

}

💾 Step 4: Add a Repository
Create a repository interface:
package com.example.demo.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import com.example.demo.model.Student;

public interface StudentRepository extends JpaRepository {
}

🌐 Step 5: Build the REST Controller
Now, expose CRUD endpoints:
package com.example.demo.controller;

import com.example.demo.model.Student;
import com.example.demo.repository.StudentRepository;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/students")
public class StudentController {

private final StudentRepository repo;

public StudentController(StudentRepository repo) {
    this.repo = repo;
}

@GetMapping
public List<Student> getAllStudents() {
    return repo.findAll();
}

@PostMapping
public Student addStudent(@RequestBody Student student) {
    return repo.save(student);
}

@PutMapping("/{id}")
public Student updateStudent(@PathVariable Long id, @RequestBody Student updatedStudent) {
    return repo.findById(id)
            .map(student -> {
                student.setName(updatedStudent.getName());
                student.setEmail(updatedStudent.getEmail());
                student.setAge(updatedStudent.getAge());
                return repo.save(student);
            })
            .orElseThrow(() -> new RuntimeException("Student not found"));
}

@DeleteMapping("/{id}")
public String deleteStudent(@PathVariable Long id) {
    repo.deleteById(id);
    return "Student deleted successfully!";
}
Enter fullscreen mode Exit fullscreen mode

}

🧪 Step 6: Test Your API
Run your app and test using Postman or curl:
GET /api/students → Fetch all students
POST /api/students → Add a new student
PUT /api/students/{id} → Update a student
DELETE /api/students/{id} → Delete a student

💡 Bonus: Add Global Error Handling
Make your API error messages cleaner:
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(RuntimeException.class)
public ResponseEntity handleRuntimeException(RuntimeException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
}

🚀 Wrapping Up
You just built your first working REST API using Spring Boot and MySQL in under 15 minutes. From here, you can:
Add validation with @valid
Add JWT-based security
Deploy your app on Render or Railway for free
Spring Boot makes backend development fun and fast. Keep experimenting — every project will make you better! 🙌

🏷️ Tags

java #springboot #backend #tutorial #webdev

Top comments (0)