Delete Category Endpoint

Building on our category management endpoints from previous lessons, we'll now implement the ability to delete categories that are no longer needed.

This functionality will maintain data integrity by preventing the deletion of categories that still contain posts.

The delete endpoint ensures our blog platform remains organized while protecting against accidental data loss.

Controller Implementation

The category deletion process begins in our controller layer with a new endpoint definition.

@RestController @RequestMapping("/api/v1/categories") @RequiredArgsConstructor public class CategoryController { private final CategoryService categoryService; @DeleteMapping("/{id}") public ResponseEntity<Void> deleteCategory(@PathVariable UUID id) { categoryService.deleteCategory(id); return ResponseEntity.noContent().build(); } }

Service Interface

The service layer defines the contract for category deletion through a new method.

public interface CategoryService { // ... existing methods ... void deleteCategory(UUID id); }

Service Implementation

The service implementation enforces our business rules, particularly preventing deletion of categories with associated posts.

@Service @RequiredArgsConstructor @Transactional(readOnly = true) public class CategoryServiceImpl implements CategoryService { private final CategoryRepository categoryRepository; @Override @Transactional public void deleteCategory(UUID id) { Category category = getCategoryById(id); // Check if category has associated posts if (!category.getPosts().isEmpty()) { throw new IllegalStateException( "Cannot delete category: " + category.getName() + ". It has associated posts."); } categoryRepository.delete(category); } private Category getCategoryById(UUID id) { return categoryRepository.findById(id) .orElseThrow(() -> new EntityNotFoundException("Category not found with id: " + id)); } }

Error Handling Enhancement

Our error controller needs to handle the new IllegalStateException that could occur during category deletion.

@RestController @ControllerAdvice @Slf4j public class ErrorController { // ... existing methods ... @ExceptionHandler(IllegalStateException.class) public ResponseEntity<ApiErrorResponse> handleIllegalStateException( IllegalStateException ex) { ApiErrorResponse error = ApiErrorResponse.builder() .status(HttpStatus.CONFLICT.value()) .message(ex.getMessage()) .build(); return new ResponseEntity<>(error, HttpStatus.CONFLICT); } }

Summary

  • Implemented DELETE endpoint returning 204 No Content on success
  • Added service layer validation preventing deletion of categories with posts
  • Enhanced error handling with specific handling for IllegalStateException
  • Maintained data integrity through proper validation checks
  • Followed RESTful conventions for resource deletion
© 2026 Devtiro Ltd. All rights reserved