REST API - 单个URL的非静态(更改)资源 - 如何设计?

时间:2015-11-08 07:08:06

标签: rest api-design

想象一下,我有一个学校的API。其中一个资源是Department,其中包含各种资源,例如Professors的集合,以及#34;主教授&#34}。

部门看起来像这样:

{
    "_links": {
                  "self": "http://myapi.com/department/math"
    }
    "name": "Math Department",
    "headProfessor": {
                "_links": {
                              "self": "http://myapi.com/professor/id/2",
                              "headProfessor": "http://myapi.com/headprofessor/department/math"
                },
                "name": "George Patton",
                "id": "2"
    }
    "professors": {
        "_links": {
                      "self": "http://myapi.com/professors/department/math"
        },
        "_collectionData": [
            {
                "_links": {
                      "self": "http://myapi.com/professor/id/1"
                },
                "name": "John Doe",
                "id": "1"
            },
            {
                "_links": {
                      "self": "http://myapi.com/professor/id/2"
                },
                "name": "George Patton",
                "id": "2"
            },
            {
                "_links": {
                      "self": "http://myapi.com/professor/id/3"
                },
                "name": "Paul Simon",
                "id": "3"
            }
        ]
    }
}

我的问题是关于" headProfessor"和链接。 "主教授"?的规范链接是什么?它是http://myapi.com/professor/id/1还是http://myapi.com/headprofessor/department/math?我应该两个都在吗?或者只是一个必要的?是否有更好的方式来代表" head"或者" top"某些东西,基本上是一个可以改变资源的网址,因为它代表了一种关系,而不是一种静态资源?

注意

是的,我确实首先在url中使用资源指示符,因为它为资源指示符提供了每个url中的相同位置。但我的问题与此无关。这只是品味和风格的问题。

1 个答案:

答案 0 :(得分:1)

首先,系有教授,反之亦然,所以你的API应该像这样设计

http://myapi.com/departments   -> GET all departments
http://myapi.com/departments/{departmentId}/professors ---> POST to add a professor to a department , body of POST has the rank of professor has HOD, or staff
http://myapi.com/departments/{departmentId}/professors ---> GET should get all professors of that department
http://myapi.com/departments/{departmentId}/professors?rank=hod ---> Should give you the HOD 
http://myapi.com/departments/{departmentId}/professors/{professorId} ---> PUT to change rank of Professor
http://myapi.com/departments/{departmentId}/professors/{professorId} ---> DELETE to remove professor from Department if he retires or moves to another college,etc.