Creating REST APIs Using Spring Boot

Creating REST APIs Using Spring Boot

Introduction

Spring Boot simplifies Java-based application development. It is widely used to create RESTful APIs due to its auto-configuration, embedded server, and minimal setup. In this article, you'll learn how to build a simple REST API using Spring Boot.


☑️ What is a REST API?

REST (Representational State Transfer) is an architectural style for designing web services. REST APIs use HTTP methods to perform CRUD operations:

  • GET – Read data

  • POST – Create new data

  • PUT – Update existing data

  • DELETE – Remove data


πŸ› ️ Setting Up Spring Boot Project

1. Using Spring Initializr

Go to https://start.spring.io and select:

  • Project: Maven

  • Language: Java

  • Spring Boot: Latest stable

  • Dependencies: Spring Web, Spring Boot DevTools, Spring Data JPA, H2 Database (or MySQL)

Generate the project and unzip it.


πŸ“ Project Structure

src/ └── main/ ├── java/ │ └── com.example.demo/ │ ├── controller/ │ ├── service/ │ ├── model/ │ └── repository/ └── resources/ └── application.properties

✍️ Define the Model

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

πŸ—ƒ️ Create the Repository

// repository/StudentRepository.java
public interface StudentRepository extends JpaRepository<Student, Long> { }

πŸ“¦ Write the Service Layer

// service/StudentService.java @Service public class StudentService { @Autowired private StudentRepository studentRepository; public List<Student> getAllStudents() { return studentRepository.findAll(); } public Student getStudent(Long id) { return studentRepository.findById(id).orElse(null); } public Student createStudent(Student student) { return studentRepository.save(student); } public void deleteStudent(Long id) { studentRepository.deleteById(id); } public Student updateStudent(Long id, Student student) { student.setId(id); return studentRepository.save(student); } }

🌐 Build the REST Controller

// controller/StudentController.java @RestController @RequestMapping("/api/students") public class StudentController { @Autowired private StudentService studentService; @GetMapping public List<Student> getAllStudents() { return studentService.getAllStudents(); } @GetMapping("/{id}") public Student getStudent(@PathVariable Long id) { return studentService.getStudent(id); } @PostMapping public Student createStudent(@RequestBody Student student) { return studentService.createStudent(student); } @PutMapping("/{id}") public Student updateStudent(@PathVariable Long id, @RequestBody Student student) { return studentService.updateStudent(id, student); } @DeleteMapping("/{id}") public void deleteStudent(@PathVariable Long id) { studentService.deleteStudent(id); } }

⚙️ Configure Application Properties

# application.properties 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.h2.console.enabled=true

▶️ Run the Application

Run the main class:

@SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }

πŸ§ͺ Testing the API

Use Postman, cURL, or any REST client:

  • GET /api/students → List all students

  • POST /api/students → Add a student

  • GET /api/students/{id} → Get a student

  • PUT /api/students/{id} → Update a student

  • DELETE /api/students/{id} → Delete a student


πŸ“ Error Handling (Optional)

Add global exception handling using @ControllerAdvice for a cleaner API.

@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(EntityNotFoundException.class) public ResponseEntity<String> handleNotFound(EntityNotFoundException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND); } }

πŸš€ Deploying Spring Boot APIs

You can deploy to:

  • Heroku

  • AWS (Elastic Beanstalk or EC2)

  • Docker + Cloud Platforms

Package your app using:

mvn clean install java -jar target/demo-0.0.1-SNAPSHOT.jar

Conclusion

Spring Boot makes it easy to create RESTful APIs in Java. With minimal configuration and a clean structure, you can build scalable backend services for your web or mobile applications.

Whether you're creating a student app or an enterprise service, Spring Boot is a reliable framework to get your APIs up and running quickly. 



Read More 




Comments

Popular posts from this blog

Tosca System Requirements and Installation Guide (Step-by-Step)

How to Install Selenium for Python Step-by-Step

Tosca Commander: A Beginner’s Overview