Spring REST URI存在检查

让我们假设一个简单的基于Spring的RESTful API,带有一些嵌套资源。

  • A User is the root entity created by everyone to access the API
  • Each User can create Posts, therefor a Post can't exist without a creator
  • A User can also comment existing Posts, therefor a Comment belongs to a Post

对于此API,我选择了以下RESTful路由:

  • /api/users for User
  • /api/users/{userId}/posts for Post
  • /api/users/{userId}/posts/{postId}/comments for Comment

About my question, should I validate that the parent resources exists? For example for the request GET /api/users/2/posts/3/comments/7, should I ensure that the entities User(2) and Post(3) also exists? Do I also have to make sure that the entities are related to each other and not any x arbitrary resources that exist are used?

@PostMapping("/api/users/{userId}/posts/{postId}/comments")
public void create(@PathVariable("userId") Long userId, @PathVariable("postId") Long postId, @RequestBody CommentPayload payload) {

    // userService.existsByIdWithPostId(userId, postId); ???

    commentService.createForPost(postId, payload);
}

To create the comment in the database, the userId is completely irrelevant, the postIdis needed only. Should I still make sure that user with userId X exists and has a post with postId Y or should ignore it?

If yes how could I do this elegant? Because growing JPA/Repository queries like Optional<Comment> findByUserIdAndPostIdAndId(...) doesn't seem to be an solution... Should the validation then take place in several queries? The inclusion of all parents' ids complicates the actual query immense. In addition, the identifiers must be passed through all layers (service, security), which complicates the internal API.