我对 REST API 开发还很陌生。我决定使用 Spring Boot 创建一个博客应用程序,但我真的在为应用程序的设计和结构而苦苦挣扎。
现在我的应用程序由帖子和评论模型和存储库组成。对于这两个模型,我创建了服务类(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) { ... }
现在我开始回答我的问题了。我想知道向帖子添加评论的正确设计是什么。
- 我应该使用 CommentController 类公开 Comment 的所有 CRUD 方法并使用 create 方法吗?
- 添加新方法可以吗
addComment
到 PostController 它将创建一个新的评论?
在我看来,向帖子添加评论属于帖子,但我真的不知道。
有人可以就此事给我一些建议吗?
多谢!
Bye,
Tom
如果我是你,我会考虑 REST 设计原则开放API规范 http://spec.openapis.org/oas/v3.0.3并将遵循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 设计的注释,我会将它们包含在posts资源,并且会添加这些相应的 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 命名约定here https://restfulapi.net/resource-naming/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)