繁体   English   中英

RestController 设计之争——Spring 启动 REST API

[英]RestController design struggle - Spring Boot REST API

我对 REST API 开发很陌生。 我决定使用 Spring Boot 创建一个博客应用程序,我真的在为我的应用程序的设计和结构而苦苦挣扎。

现在我的应用程序由 Post 和 Comment 模型和存储库组成。 对于这两种模型,我都创建了服务类(PostService 和 CommentService)。 在这些类中,我拥有所有的业务逻辑(现在只是简单的 CRUD)。

现在我对我的@RestControler for Posts 的设计摸不着头脑。 在 PostController 中,我公开了这些操作:

@PostMapping("/api/posts/create")
public Post create(@RequestBody Post post) { ... }

@GetMapping("/api/posts")
public List<Post> findAll() { ... }

@GetMapping("/api/posts/{id}")
public Post findById(@PathVariable("id") Long id) { ... }

@PutMapping("/api/posts/{id}")
public Post update(@RequestBody Post post) { ... }

@DeleteMapping("/api/posts/{id}")
public void delete(@PathVariable Long id) { ... }

现在我要回答我的问题了。 我想知道在帖子中添加评论的正确设计是什么。

  1. 我应该使用 CommentController class 公开所有评论的 CRUD 方法并使用 create 方法吗?
  2. 可以向 PostController 添加新方法addComment来创建新评论吗?

在我的脑海中为帖子添加评论属于帖子,但我真的不知道。

有人能给我一些关于这个问题的建议吗?

非常感谢!

再见,汤姆

如果我是你,我会考虑 OpenAPI规范中的 REST 设计原则,并遵循resource -> sub-resource -> method||identifier模式。 出于可读性和理解的目的,这可能是最 KISS 和最干净的设计。

@PostMapping("/api/posts/") //you don't need /create as a separate URI
public Post create(@RequestBody Post post) { ... }

@GetMapping("/api/posts") //This is OK.
public List<Post> findAll() { ... }

@GetMapping("/api/posts/{id}") //OK, however {id} should be optional, hence you can combine this and upper methods in one method.
public Post findById(@PathVariable("id") Long id) { ... }

@PutMapping("/api/posts/{id}") //OK.
public Post update(@RequestBody Post post) { ... }

@DeleteMapping("/api/posts/{id}") //OK.
public void delete(@PathVariable Long id) { ... }

现在,对于 API 设计的评论,我会将它们包含在帖子资源下,并添加这些相应的 URI:

@GetMapping("/api/posts/{id}/comments/{commendId}") //commentId is optional
@PostMapping("/api/posts/{id}/comments/") //you don't need any {commendId} here, just post the payload

等等。我希望你能想出方法签名和其他方法映射。

您还可以在此处查看 RESTful 命名约定

老实说,我不认为有人可以在这里给你完美的答案。 这通常是个人决定。 通常,您可以对 REST API 说以下内容。

  • 路径应该只代表您在数据库中的数据结构。 例如/api/posts

  • 路径中没有动词。 想做的事情应该由 RequestType 处理(GET、POST、PUT、PATCH、DELETE 等)

现在谈谈你的情况。 我真的很能理解你为什么挣扎。 我认为这里有两个选择:

  1. 帖子控制器

    您说Comment始终是Post的一部分,因此您像这样设计您的 API。

     @PostMapping("/api/posts/{id}/comment") public Comment create(@PathVariable Long id), @RequestBody Comment comment) {... }
  2. 评论控制器

    您将Comment作为自己的 object 处理,而Post只是您通过属性添加到它的关系。

     @PostMapping("/api/comments") public Comment create(@RequestBody Comment comment) {... }

所以它总是一个子集自己的 Object 结构 我认为在这种情况下,我更喜欢选项 2,因为我认为您想在此 object 上执行更多操作。

您也可以设计您的 API,使每个 Controller 都以 object 开头,将被处理/api/OBJECT/xxx/yyy

更新

在阅读了@gulliva 的评论后,我认为还有一个好方法是使用这个 URL @PostMapping("/api/posts/{id}/comment")但把它放在CommentsController中。 我认为这是一个好方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM