据我所知,每个资源应该只有一个规范路径.因此,在下面的示例中,优秀的URL模式是什么?
以公司的休息代表为例.在这个假设的例子中,每个公司拥有 0个或更多部门,每个部门拥有 0个或更多员工.
没有关联公司,部门就不可能存在.
没有相关部门,员工就不能存在.
现在我会找到资源模式的自然表示.
/companies 一系列公司 - 接受新公司的接受.获取整个系列./companies/{companyId}一家公司.接受GET,PUT和DELETE/companies/{companyId}/departments接受新项目的POST.(在公司内部创建一个部门.)/companies/{companyId}/departments/{departmentId}//companies/{companyId}/departments/{departmentId}/employees/companies/{companyId}/departments/{departmentId}/employees/{empId}考虑到约束,在每个部分中,我觉得如果有点深度嵌套,这是有道理的.
但是,如果我想列出(GET)所有公司的所有员工,我的困难就来了.
最合适的资源模式将映射到/employees(所有员工的集合)
这是否意味着我应该/employees/{empId}也是因为如果是这样,那么有两个URI可以获得相同的资源?
或者整个架构可能会被展平,但这意味着员工是一个嵌套的顶级对象.
在基本级别,/employees/?company={companyId}&department={deptId}返回与最深层嵌套模式完全相同的员工视图.
URL模式的最佳实践是什么,其中资源由其他资源拥有但应该可以单独查询?
更新:请参阅下面的答案,看看我做了什么.
我正在访问一个REST服务,它公开了这两个资源,一个父资源和一个子资源:
/users
/users/{userId}/account
Run Code Online (Sandbox Code Playgroud)
因此资源"帐户"不嵌套在资源"用户"中,它必须由第二个请求访问.这里有REST API的例子,例如这里
我使用这些模型将用户及其帐户映射到Ext Js 4数据模型:
用户
Ext.define("MyApp.model.User", {
extend: "Ext.data.Model",
fields: [ { name: "id", type: "string" }],
associations: [{
model: "MyApp.model.Account",
name: "account",
type: "hasOne",
reader: "json",
getterName: "getAccount",
setterName: "setAccount",
foreignKey: "accountId"
}
],
proxy: {
type: "rest",
url: "/rest/users",
reader: {
type: "json",
totalProperty: "total",
root: "users"
}
}
});
Run Code Online (Sandbox Code Playgroud)
帐户
Ext.define("MyApp.model.Account", {
extend: "Ext.data.Model",
fields: [ { name: "id", type: "string" }],
belongsTo: "MyApp.model.User",
proxy: {
type: "rest",
reader: { type: "json"} …Run Code Online (Sandbox Code Playgroud) 将带有嵌套对象的对象传递给ASP.NET Web API GET方法的URL语法是什么?这可能吗?
http://mydomain/mycontroller?...
Mycontroller GET方法:
public void Get([FromUri]MyType myType) { ... }
Run Code Online (Sandbox Code Playgroud)
C#类型:
public class MyType
{
public string Name { get; set; }
public NestedType Foo { get; set; }
}
public class NestedType
{
public int Bar { get; set; }
}
Run Code Online (Sandbox Code Playgroud) 我正在学习REST原则,我对使用复杂资源有疑问.
假设我们有两个资源,Foo和Bar,对于每个Foo,我必须有一个Bar.我想使用我的API将bar的依赖关系从foo清除到开发人员,因此:
1)我将使用从Foo实例到Bar实例的链接,反之亦然
GET /foos/1
Foo: {
'name': 'Foo instance',
'rel_bar': '/foos/1/bar'
}
GET /foos/1/bar
Bar: {
'name': 'Bar instance',
'rel_foo': '/foos/1',
}
Run Code Online (Sandbox Code Playgroud)
2)我将使用一个URI模板,显示从Foo到Bar的依赖关系(这仅适用于人类,因为REST应该对REST不透明).
/foos --> Foo resource collection
/foos/{foo_id} --> An instance of a Foo resource
/foos/{foo_id}/bar --> The bar instance associated to the foo instance foo_id
Run Code Online (Sandbox Code Playgroud)
所以再一次,没有相应的foo就没有吧.
现在我想创建一个Foo资源.
POST /foos
{
'name': 'Yet again another foo instance',
}
Run Code Online (Sandbox Code Playgroud)
并让服务器创建相应的Bar默认(或空)资源,因此下次读取时会给出:
GET /foos/2
{
'name': 'Yet again another foo instance',
'rel_bar': '/foos/2/bar'
}
Run Code Online (Sandbox Code Playgroud)
和...
GET /foos/2/bar
{
'name': null, --> …Run Code Online (Sandbox Code Playgroud)