【发布时间】:2014-01-17 15:17:43
【问题描述】:
我已经阅读了一些关于 RESTful API 设计的有趣教程,其背后的概念非常清楚......但现在让我们通过 Play 将其付诸实践吧。
假设我们想要实现一个 RESTful API,它提供了与用户打交道的功能。让我们从模型开始。这是Address 类:
case class Address(
id: Int,
street: String,
zip: String,
city: String,
country: String
)
...这里是User 类:
case class User(
id: Int,
email: String,
firstName: String,
lastName: String,
addresses: Array[Int]
// addresses: Array[Address] would this option be better?
)
...最后是路线:
# Creates a new user
POST /users controllers.users.create
# Gets the user identified by the specified id
GET /users/:userId controllers.users.find(userId)
# Modifies the user identified by the specified id
PUT /users/:userId controllers.users.update(userId)
# Deletes the user identified by the specified id
DELETE /users/:userId controllers.users.delete(userId)
第一个问题是:我如何通过电子邮件检索用户,让我的 API 投诉符合 REST 规则?以下内容不起作用,因为它与GET users/:userId 冲突:
# Gets the user identified by the specified email address
GET /users/:email controllers.users.findByEmail(email)
目前我想到的两个选项是:
GET /users controllers.users.list(Option[email])
或
GET /users/:email/xxx controllers.users.findByEmail(email)
其中xxx 应该是一种虚拟资源。有什么建议吗?
我的第二个也是最后一个问题是:我应该如何管理用户地址?我应该得到一个User,将新的Address 添加到User.addresses,然后用PUT 更新User?
PUT /users/:userId controllers.users.update(userId)
...或者我应该创建一个特定的控制器来管理这样的用户地址?
POST /users/:userId/addresses/ controllers.addresses.create(userId)
我个人更喜欢第二种选择......但也许有更好的选择。
【问题讨论】:
标签: scala rest playframework