List Tags Endpoint

In our previous lessons, we implemented user authentication and security for our blog platform.

Now we'll create an endpoint to list all tags with their associated post counts, providing a foundation for content discovery.

This endpoint will enable users to explore blog content through tag-based navigation and filtering.

Tag Response Structure

A dedicated response DTO ensures consistent representation of tag data in our API:

@Data @Builder @NoArgsConstructor @AllArgsConstructor public class TagResponse { private UUID id; private String name; private Integer postCount; }

Tag Mapping Configuration

The TagMapper interface handles the conversion between our domain entities and response DTOs:

@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE) public interface TagMapper { @Mapping(target = "postCount", source = "posts", qualifiedByName = "calculatePostCount") TagResponse toTagResponse(Tag tag); List<TagResponse> toTagResponseList(List<Tag> tags); @Named("calculatePostCount") default Integer calculatePostCount(Set<Post> posts) { if (posts == null) { return 0; } return (int) posts.stream() .filter(post -> PostStatus.PUBLISHED.equals(post.getStatus())) .count(); } }

Repository Enhancement

The TagRepository needs a method to efficiently fetch tags with their post counts:

@Repository public interface TagRepository extends JpaRepository<Tag, UUID> { @Query("SELECT t FROM Tag t LEFT JOIN FETCH t.posts") List<Tag> findAllWithPostCount(); }

Service Layer Implementation

The TagService interface defines the contract for tag-related operations:

public interface TagService { List<Tag> getAllTags(); }

The TagServiceImpl implements the tag retrieval logic with proper transaction management:

@Service @RequiredArgsConstructor public class TagServiceImpl implements TagService { private final TagRepository tagRepository; @Override @Transactional(readOnly = true) public List<Tag> getAllTags() { return tagRepository.findAllWithPostCount(); } }

Controller Implementation

The TagController handles HTTP requests for tag operations:

@RestController @RequestMapping("/api/v1/tags") @RequiredArgsConstructor public class TagController { private final TagService tagService; private final TagMapper tagMapper; @GetMapping public ResponseEntity<List<TagResponse>> getAllTags() { List<Tag> tags = tagService.getAllTags(); return ResponseEntity.ok(tagMapper.toTagResponseList(tags)); } }

Summary

  • Created response DTO and mapper for consistent tag representation
  • Implemented service layer with transaction management for tag operations
  • Added controller endpoint for retrieving all tags with post counts
  • Enhanced repository with efficient post count fetching
  • Integrated with existing security configuration for public access
© 2026 Devtiro Ltd. All rights reserved