【问题标题】:Is this the correct way to design REST API URI's?这是设计 REST API URI 的正确方法吗?
【发布时间】:2021-11-14 19:43:52
【问题描述】:

所以我正在做一个小项目。这是一个 REST API,将充当“买卖”网站的后端。 目前我有两个主要资源:用户和广告。 一个用户可以创建许多广告。每个广告都是由某个用户制作的。

有人可以验证以下端点是否遵循 REST 原则并且它们有意义?如果您认为它们看起来不正确,请提出替代方案。

//Users
Create a user - POST /api/users - 
user details are passed as json in request body.

Get a user by id - GET /api/users/{user_id} 

Get the logged in user - GET /api/users/authenticated_user -
An authentication token is passed in the request header and is used to find the user in the database.

Update the logged in user - PUT /api/users/authenticated_user - 
new user details are passed in the request body. An authentication token is passed in the request header and is used to find the user in the database.

Delete the logged in user DELETE /api/users/authenticated_user -
 An authentication token is passed in the request header and is used to find the user in the database.

Get an ads user - GET /api/ads/{ad_id}/user
    

//Ads
Get all ads - GET /api/ads

Create an ad - POST api/ads -
 ad details are passed in request body and the user_id of the ad creater is got from the authentication token passed in request header. Would this endpoint make more sense to be something like: /api/users/authenticated_user/ads

Get an ad by id - GET /api/ads/{ad_id}

Update an ad - PUT api/ads/{ad_id} - 
ad details are passed in request body and the user_id of the ad creater is got from the authentication token passed in request header to make sure the ad was created by him/her. Would this make more sense to be api/users/authenticated_user/ads/{ad_id}

Delete an ad - DELETE api/ads/{ad_id} - 
The user_id of the ad creater is got from the authentication token passed in request header to make sure the ad was created by him/her. Would this make more sense to be api/users/authenticated_user/ads/{ad_id}

Get a users ads by id - GET /api/users/{user_id}/ads

Get logged in users ads - GET /api/users/authenticated_user/ads -

身份验证令牌在请求标头中传递,用于在数据库中查找用户。

在某些端点中使用身份验证令牌的原因是因为客户端无法访问登录用户的 user_id,只能访问身份验证令牌。 谢谢,非常感谢您的意见。

【问题讨论】:

  • 这将倾向于意见。嵌入在路线信息中的问题基本上是不可见的,除非有人碰巧滚动,顺便说一句——虽然它不会改变问题的性质,但如果页面边缘有问题,人们可能看不到它们。跨度>
  • @DaveNewton 谢谢,我在那里改变了它,希望它更具可读性。我知道在处理 REST URI 时,它可能有点基于意见,但这是我在可接受范围内所拥有的。谢谢

标签: rest web-applications


【解决方案1】:

有人可以验证以下端点是否遵循 REST 原则并且它们有意义?

REST 没有“端点”,它有resources。 (Fielding, 2018)

任何符合RFC 3986“遵循 REST 原则”中描述的生产规则的标识符。


“REST 原则”会告诉您设计一个网站,其中包含相互关联的 hypertext documents 和 web forms,并利用在网络上共享的 standards。

但是 REST 没有告诉你的是你的网站上应该有哪些页面,或者你的网页应该使用什么拼写约定,或者如何弥合网站之间的差距和interesting business activities in your domain。


您想为资源标识符使用的任何拼写约定都是很好。机器不关心标识符的拼写是否与资源的语义匹配。

人类倾向于更喜欢人类可读的标识符 - 当您可以从标识符拼写中猜出资源是什么时,访问日志和浏览器历史记录更容易分析。

URI templates 可以轻松描述的标识符系列使许多映射琐事(如路由)变得更加容易。

当然,如果bookmarks remain stable 真的很有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-07
    • 2012-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-25
    相关资源
    最近更新 更多