RESTful API设计:ID值为;“拥有”;资源
在设计restful API时,在设计URI时要考虑资源所有权。在我的例子中,我正在开发一个API,其中两个实体是人员和地址。每个人可以有多个地址,因此在数据库中,他们将位于单独的表中 通常我只使用自动递增键,因此每次添加新记录都会增加ID号 我的想法是,如果我使用这种方法,它将有效地生成如下URI:RESTful API设计:ID值为;“拥有”;资源,api,rest,Api,Rest,在设计restful API时,在设计URI时要考虑资源所有权。在我的例子中,我正在开发一个API,其中两个实体是人员和地址。每个人可以有多个地址,因此在数据库中,他们将位于单独的表中 通常我只使用自动递增键,因此每次添加新记录都会增加ID号 我的想法是,如果我使用这种方法,它将有效地生成如下URI: /people/11/address/52 在这种情况下,person11没有52个地址。只有11个人,他的地址是52 另一方面是我是否会使用这样的URI。地址通常不会由客户端自己检索,而是作为单
/people/11/address/52
在这种情况下,person
11没有52个地址。只有11个人,他的地址是52
另一方面是我是否会使用这样的URI。地址通常不会由客户端自己检索,而是作为单个API调用检索的person对象的一部分(/people/11
将检索与此人关联的所有地址)
无论如何,我想这里的问题是关于最佳实践的。看到另一个实体拥有这样的ID值是常见的吗?这方面的一般做法是什么?是的,这是在API中应用多对多关系的正确方法。在返回值时,请记住检查id2是否属于id1
要检索所有地址,正确的调用是/people/11/addresses
。然后你就知道你必须调用一个加入查询。当你以个性化的方式为人物实体返回地址的详细信息时,你通常会使用类似于:/people/11/addresses/52的资源
例如,如果您有实体:可以有地址的人员和办公室;对于人员,您只想显示国家/地区;对于办公室,您想显示地址的所有详细信息
另一方面,如果不需要定制,也可以使用类似于:/address/12的url,因为这样更容易缓存响应
客户端通常不会自行检索地址,
但作为单个API调用检索的person对象的一部分
(/people/11将检索与此人关联的所有地址)
如果是这种情况,您可以省略详细的地址url。您的方法是正确的。
还有一些一般规则():
网上也有很多参考资料。佩奇是一个好的开始。
这些也很有用:,谢谢,这太棒了。读了一遍,我又想到了两个问题。1) 链接头中的分页是什么意思?我正在考虑使用请求参数来实现这一点,那么我该怎么做呢?2) REST安全性/身份验证是我目前正在研究的问题。我通常只是使用SpringSecurity来实现这一点,有没有什么技巧可以让您以RESTful的方式使用它?特别是关于如何维护无状态?链接头由引入并旨在指示Web上资源之间的关系:Link:;rel=“下一步”;rel=“last”
而基于令牌的身份验证是API中的令牌:https://api.test.com/get/some/info?token=12345
这就是为什么您总是需要ssl!隐藏令牌!
- An API is a user interface for a developer - so put some effort into making it pleasant
- Use RESTful URLs and actions
- Use SSL everywhere, no exceptions
- An API is only as good as its documentation - so have great documentation
- Version via the URL, not via headers
- Use query parameters for advanced filtering, sorting & searching
- Provide a way to limit which fields are returned from the API
- Return something useful from POST, PATCH & PUT requests
- HATEOAS isn't practical just yet
- Use JSON where possible, XML only if you have to
- You should use camelCase with JSON, but snake_case is 20% easier to read
- Pretty print by default & ensure gzip is supported
- Don't use response envelopes by default
- Consider using JSON for POST, PUT and PATCH request bodies
- Paginate using Link headers
- Provide a way to autoload related resource representations
- Provide a way to override the HTTP method
- Provide useful response headers for rate limiting
- Use token based authentication, transported over OAuth2 where delegation is needed
- Include response headers that facilitate caching
- Define a consumable error payload
- Effectively use HTTP Status codes