'Where to place the resource root id in the url?

I have resources linked like this: A->B->C->D

I want to design a REST API to retrieve the D elements inside of A

Which is the best design approach?

  1. api/v1/A/{a-id}/D

  2. api/v1/D/A/{a-id}

  3. api/v1/D?AId={a-id}

The first one look nice but the project (asp net core) has a controller for every resource, so adding the action in controller A doesn't feel right.



Solution 1:[1]

I think you could try as follow: api/v1/A/id

A:

 {
            "someproperty":somevalue,
            
            "links": [
                {"rel":"A","href":"api/v1/D/someid", "action":"GET" },
                {"rel":"A","href":"api/v1/D/someid", "action":"PUT" }
            ]
        }

The official document about restfulapi: https://docs.microsoft.com/en-us/azure/architecture/best-practices/api-design

Solution 2:[2]

"REST" is the architectural style on which the HTTP protocol was built. Every web page was intended to be "RESTful" and REST itself says nothing about what the API should look like. The query is obviously about modern APIs. A modern API MUST adhere to the RFCs and at the same time SHOULD adhere to common conventions. Common conventions make the REST API understandable to consumers. Further, I am answering with respect to modern APIs.


If the D elements are in composition with A, then you can consider everything as one resource. A common example is an invoice and invoice items. In other cases I recommend to create two resource url.

GET api/v1/a/{aid}
GET api/v1/d?aid={aid}

This solution provides the greatest flexibility and reduces the risk of backward compatibility issues. Think not how to version, but how to avoid versioning.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ruikai Feng
Solution 2 Miroslav Holec