Hierarchical RESTful URL design

后端 未结 3 1741
青春惊慌失措
青春惊慌失措 2020-12-04 16:00

I have perused the questions asked about this, but I still don\'t have a definitive answer.

I have an application and would like to build a RESTful API to expose a s

相关标签:
3条回答
  • 2020-12-04 16:15

    Nothing wrong in this design.But this creates long URL which sometime are difficult to understand and the user of the API needs to know the hierarchy.Moreover the consumer of the API need to write more code in little bit non-standard way(Even though it can be done, but will be little messy). Think this from a different perspective You have three resources and each has its own identity.So if we refactor the above URI's it will looks like below (I am demonstrating only GET)

    User Resource:

    Get users list

      GET example.com/api/users
    

    Get specific user

      GET example.com/api/users/{username}
    

    Report Resource:

    Get all reports

     GET example.com/api/reports
    

    Get a specific report

     GET example.com/api/reports/{report_id}
    

    Photo Resources

    All Photos

    GET example.com/api/photos
    

    Specific Photo

    GET example.com/api/photos/{photo_id}
    

    User All Reports

    GET example.com/api/reports?username={userName}
    

    Specific report of a user

    GET example.com/api/report?username={userName}&report_id={reportId}
    

    User All Photos

    GET example.com/api/photos?username={userName}
    

    User All Photos for a report id (You may not need user Name if report_id is unique irrespective of the user, which will further simplify the URI)

    GET example.com/api/photos?username={userName}&report_id={reportId}
    

    All photos of a report

    GET example.com/api/photos?report_id={reportId}
    

    This simplifies the understanding and more standard code can be written on the consumer side using this approach.

    0 讨论(0)
  • 2020-12-04 16:32

    I don't see anything wrong with your scheme.

    Most frameworks nowadays use a similar standard for specifying url's (like Django).

    In my personal opinion, it makes the URL more readable and a bit nicer for the user.

    0 讨论(0)
  • 2020-12-04 16:33

    IMHO you are modelling it well.

    Regarding 1 I'd rather go with resource/id rather than query param. But one thing you must have in mind when modelling is the cache mechanism by proxy and so on. So do not forget the headers.

    I go for query params for filtering and those sorts.

    About the login, the credentials should be in the headers, and no specific resource is needed. Just apply per resource security.

    0 讨论(0)
提交回复
热议问题