RESTful API routes design: nested vs. non-nested

前端 未结 3 937
星月不相逢
星月不相逢 2021-02-05 07:26

My question is about the advantages of nesting resources when building URLs for API purposes. Consider the following two alternatives for accessing an employee resource:

3条回答
  •  再見小時候
    2021-02-05 07:28

    What happens if you want do drill down a couple more levels?

    /api/addresses?departmentId=1&employeeId=2&addressId=3

    vs

    /api/departments/1/employees/2/addresses/3

    The Address endpoint suddenly becames bloated with parameters.

    Also, if you're looking at the Richardson Maturity Model level 3, RESTful APIs are meant to be discoverable through links. For example, from the top level, say /api/version(/1), you would discover there's a link to the departments. Here's how this could look in a tool like HAL Browser:

    "api:department-query": {
      "href": "http://apiname:port/api/departments?pageNumber={pageNumber}&pageSize={pageSize}&sort={sort}"
    },
    "api:department-by-id": {
      "href": "http://apiname:port/api/departments?departmentId={departmentId}"
    }
    

    (either a query that might list them all, in a paged manner eventually, or a parameterized link that would go directly to a specific department, provided you know the id).

    The advantage here would be that the client would only need to know the relationship (link) name, while the server would be mostly free to alter the relationship (and resource) url.

提交回复
热议问题