Spring Boot makes it super simple to create RESTful APIs quickly with minimal configuration. Let’s break it down step by step:
REST API
A REST API is a web service that follows REST principles and allows clients (like browsers or mobile apps) to perform operations (like GET, POST, PUT, DELETE) on resources via HTTP.
Why Spring Boot
- Auto-configuration: Spring Boot reduces boilerplate setup.
- Embedded server: Comes with Tomcat/Jetty, no need to deploy WAR files.
- Production-ready: Has built-in monitoring and configuration support.
Basic Steps to Build a REST API
Create a Spring Boot project
- Open IntelliJ IDEA.
- Go to File → New → Project.
- Select Spring Initializr.
- Fill in:
- Group:
com.example
- Artifact:
restapi
- Group:
- Add dependencies:
- Spring Web
- (Optional) Spring Boot DevTools
- Click Finish to generate your project.
Create a Model Class
Create a simple model class inside the model
package:
1 2 3 4 5 6 7 8 |
package com.example.restapi.model; public class Employee { private Long id; private String name; private String role; // Getters and Setters } |
Build the REST Controller
Create a controller class inside the controller
package:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package com.example.restapi.controller; import com.example.restapi.model.Employee; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping("/api/employees") public class EmployeeController { private List<Employee> employees = new ArrayList<>(); @GetMapping public List<Employee> getAllEmployees() { return employees; } @PostMapping public Employee addEmployee(@RequestBody Employee employee) { employees.add(employee); return employee; } } |
@RestController
: Combines@Controller
+@ResponseBody
.@GetMapping
,@PostMapping
: Map HTTP methods (GET, POST) to Java methods.@RequestBody
: Binds JSON payload from the request to a Java object.
Run the Application
- Right-click the main
RestapiApplication.java
class. - Click Run ‘RestapiApplication.main()’.
- Open your browser or use Postman:
- GET
http://localhost:8080/api/employees
- POST
http://localhost:8080/api/employees
with JSON body like:
12345{"id": 1,"name": "Alice","role": "Developer"}
- GET