✅ API (Application Programming Interface)
Là một giao diện giao tiếp giữa hai phần mềm hoặc hệ thống. Trong lập trình web, API thường là nơi ứng dụng frontend gửi yêu cầu để nhận dữ liệu từ backend.
✅ REST API (Representational State Transfer)
Là một loại API hoạt động dựa trên giao thức HTTP, với nguyên tắc:
- Stateless: Mỗi request độc lập
- Resource-based: Dữ liệu là tài nguyên (resource)
- HTTP method: GET, POST, PUT, DELETE
🧑💻 Tạo REST API cơ bản
a. Tạo một lớp GiangVien
public class GiangVien {
private Long id;
private String hoTen;
private String donVi;
// Constructors, Getters, Setters
}
b. Controller – REST API
@RestController
@RequestMapping("/api/giangvien")
public class GiangVienController {
private List<GiangVien> list = new ArrayList<>(List.of(
new GiangVien(1L, "Nguyễn Văn A", "Khoa CNTT"),
new GiangVien(2L, "Trần Thị B", "Khoa Toán")
));
// 1. GET - Lấy danh sách
@GetMapping
public List<GiangVien> getAll() {
return list;
}
// 2. GET - Lấy theo ID
@GetMapping("/{id}")
public ResponseEntity<GiangVien> getById(@PathVariable Long id) {
return list.stream()
.filter(gv -> gv.getId().equals(id))
.findFirst()
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
// 3. POST - Thêm mới
@PostMapping
public ResponseEntity<GiangVien> create(@RequestBody GiangVien gv) {
gv.setId((long) (list.size() + 1)); // Gán ID giả lập
list.add(gv);
return ResponseEntity.status(HttpStatus.CREATED).body(gv);
}
// 4. PUT - Cập nhật
@PutMapping("/{id}")
public ResponseEntity<GiangVien> update(@PathVariable Long id, @RequestBody GiangVien updated) {
for (int i = 0; i < list.size(); i++) {
GiangVien current = list.get(i);
if (current.getId().equals(id)) {
updated.setId(id);
list.set(i, updated);
return ResponseEntity.ok(updated);
}
}
return ResponseEntity.notFound().build();
}
// 5. DELETE - Xóa
@DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable Long id) {
boolean removed = list.removeIf(gv -> gv.getId().equals(id));
if (removed) return ResponseEntity.noContent().build();
else return ResponseEntity.notFound().build();
}
}
📦 Kết quả các endpoint
Method | URL | Mô tả |
---|---|---|
GET | /api/giangvien | Lấy danh sách giảng viên |
GET | /api/giangvien/1 | Lấy giảng viên theo ID |
POST | /api/giangvien | Thêm mới giảng viên |
PUT | /api/giangvien/{id} | Cập nhật giảng viên |
DELETE | /api/giangvien/{id} | Xóa giảng viên |
🛠 Cách test:
Bạn có thể dùng Postman, [cURL] hoặc công cụ khác như Swagger UI để test API này.
🔰 Ghi chú:
- Đây là demo dùng List trong bộ nhớ (memory).
- Trong thực tế bạn nên dùng JPA + MySQL với
@Entity
,@Repository
,@Service
.