让我们假设一个简单的基于Spring的RESTful API,带有一些嵌套资源。
- A
User
is the root entity created by everyone to access the API - Each
User
can createPosts
, therefor aPost
can't exist without a creator - A
User
can also comment existingPosts
, therefor aComment
belongs to aPost
对于此API,我选择了以下RESTful路由:
/api/users
forUser
/api/users/{userId}/posts
forPost
/api/users/{userId}/posts/{postId}/comments
forComment
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 postId
is 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.
您的API毫无意义。
REST API围绕它们所在的实体运行,因此,/ users路由应在用户上运行,/ posts路由应在post上运行,/ comments路由应在注释上运行。如有必要,每个用户都应采用适当的用户ID / PostID。如果发现自己传递了不需要的参数(如您所愿),则可能走错了路(没有双关语)。
一旦只有所需的参数,就需要对它们进行验证。
See here as an example: https://developer.wordpress.org/rest-api/reference/