Skip to content

Instantly share code, notes, and snippets.

@kavicastelo
Created April 23, 2025 17:07
Show Gist options
  • Select an option

  • Save kavicastelo/32a75d6f15e393ac329254c33ee958d5 to your computer and use it in GitHub Desktop.

Select an option

Save kavicastelo/32a75d6f15e393ac329254c33ee958d5 to your computer and use it in GitHub Desktop.
Spring Boot Learning Module 3 – Simple In-Memory CRUD API
springboot-module-3/
├── src/
│   └── main/
│       ├── java/
│       │   └── com.example.module3/
│       │       ├── controller/
│       │       │   └── TaskController.java
│       │       ├── model/
│       │       │   └── Task.java
│       │       └── SpringBootModule3Application.java
│       └── resources/
│           └── application.properties
├── README.md
└── pom.xml
public class Task {
private Long id;
@NotBlank(message = "Title is required")
private String title;
private boolean completed = false;
// constructor, getters, setters
}
@RestController
@RequestMapping("/api/tasks")
public class TaskController {
private List<Task> tasks = new ArrayList<>();
private AtomicLong idGenerator = new AtomicLong();
@PostMapping
public ResponseEntity<Task> createTask(@Valid @RequestBody Task task) {
task.setId(idGenerator.incrementAndGet());
tasks.add(task);
return ResponseEntity.status(HttpStatus.CREATED).body(task);
}
@GetMapping
public List<Task> getAllTasks() {
return tasks;
}
@GetMapping("/{id}")
public ResponseEntity<Task> getTask(@PathVariable Long id) {
return tasks.stream()
.filter(t -> t.getId().equals(id))
.findFirst()
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@PutMapping("/{id}")
public ResponseEntity<Task> updateTask(@PathVariable Long id, @RequestBody Task updatedTask) {
for (Task task : tasks) {
if (task.getId().equals(id)) {
task.setTitle(updatedTask.getTitle());
task.setCompleted(updatedTask.isCompleted());
return ResponseEntity.ok(task);
}
}
return ResponseEntity.notFound().build();
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteTask(@PathVariable Long id) {
boolean removed = tasks.removeIf(t -> t.getId().equals(id));
return removed ? ResponseEntity.noContent().build() : ResponseEntity.notFound().build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment