🌐 How to Create REST APIs in Java
In the modern software development world, REST (Representational State Transfer) has become the de facto standard for building web services. Java, being a powerful and versatile programming language, provides excellent support for creating RESTful APIs. In this comprehensive blog post, we’ll walk through the fundamental concepts and steps involved in building REST APIs in Java using Spring Boot.
🚀 What is a REST API?
A REST API is an interface that uses HTTP requests to access and manipulate data. RESTful services adhere to certain architectural principles such as:
-
Stateless communication
-
Use of standard HTTP methods (GET, POST, PUT, DELETE)
-
Resource-based URIs
-
Representation via JSON or XML
🧰 Tools and Technologies
To build REST APIs in Java, we typically use:
-
Java 17+
-
Spring Boot – for rapid application development
-
Maven or Gradle – for dependency management
-
Postman or cURL – for testing
-
IDE – like IntelliJ IDEA or Eclipse
📦 Setting Up a Spring Boot Project
You can set up a new Spring Boot project using:
-
Choose dependencies:
-
Spring Web
-
Spring Boot DevTools
-
Once downloaded, import it into your IDE.
🧑💻 Creating a RESTful API – Step by Step
1. Define a Model Class
public class Employee {
private Long id;
private String name;
private String role;
// Constructors, Getters, Setters
}
2. Create a Controller Class
@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;
}
@GetMapping("/{id}")
public Employee getEmployeeById(@PathVariable Long id) {
return employees.stream()
.filter(emp -> emp.getId().equals(id))
.findFirst()
.orElseThrow(() -> new RuntimeException("Employee not found"));
}
@PutMapping("/{id}")
public Employee updateEmployee(@PathVariable Long id, @RequestBody Employee updated) {
for (int i = 0; i < employees.size(); i++) {
if (employees.get(i).getId().equals(id)) {
employees.set(i, updated);
return updated;
}
}
throw new RuntimeException("Employee not found");
}
@DeleteMapping("/{id}")
public void deleteEmployee(@PathVariable Long id) {
employees.removeIf(emp -> emp.getId().equals(id));
}
}
🔄 HTTP Methods in REST
HTTP Method | Description | Mapping Annotation |
---|---|---|
GET | Read a resource | @GetMapping |
POST | Create a resource | @PostMapping |
PUT | Update a resource | @PutMapping |
DELETE | Delete a resource | @DeleteMapping |
🔍 Testing the API
Use Postman or curl to test endpoints:
curl -X POST http://localhost:8080/api/employees \
-H "Content-Type: application/json" \
-d '{"id":1, "name":"John Doe", "role":"Developer"}'
curl http://localhost:8080/api/employees
🛡️ Adding Exception Handling (Optional)
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<String> handleRuntimeException(RuntimeException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
}
}
🧱 Persisting Data with Spring Data JPA (Next Level)
Instead of storing data in memory, use Spring Data JPA with a database like H2 or MySQL.
-
Add dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
-
Create
EmployeeRepository
interface:
public interface EmployeeRepository extends JpaRepository<Employee, Long> {}
✅ Summary
Creating REST APIs in Java using Spring Boot is straightforward and scalable. With minimal configuration, you can have a fully functional API ready for integration. As your application grows, Spring Boot also supports additional features like validation, authentication, error handling, and much more.
Sign up here with your email
ConversionConversion EmoticonEmoticon