Search code examples
restapi-design

REST api design for variable length nested paths


I need to design an API for a resource that is nested under one or more namespaces.

For example:

   / +
     |
     +--- namespace1 
                |
                +-------- namespace2
                             |
                             +---------------- resource

where I can possibly have 0 to N namespaces.

What would be the recommended way to represent such a resource? I have considered the following approaches:

  1. represent the namespace path in the URL. e.g:

    GET /resources/namespace1/namespace2/resource
    
  • Pros: I find this the most readable
  • Cons: Still have some issues representing this approach in Open API (3.0) and in some framework DSLs. Also, something feels wrong with namespaces being under "resources"
  1. represent the namespace as a query parameter:

    GET /resources/resource?context=/namespace1/namespace2
    
  • Pros: easy to declare in Open API and DSLs
  • Cons: To my eyes, it's a little noisy
  1. represent the namespace as a header:

    GET /resources/resource
    Context: /namespace1/namespace2
    
  • Pros: easy to declare in OpenAPI and DSLs, a less noisy than #2
  • Cons: Not sure if I like the namespace hidden in the header

Is there a recommended approach for such a problem, or are there any additional patterns I may be missing?


Solution

  • I agree, #1 is the most readable, and if the technology you're using makes that easy to work with, it's worth considering. However, it's likely to result in work on the client side to form the API call correctly, which doesn't make the API particularly discoverable or documentable.

    #3 is really just a variation of #2. You've only chosen to express the namespace in the header instead of a query parameter. In either case, it doesn't make the client have to assemble the URI, but clients would probably prefer to send a "clean" request for a URI than add in headers.

    Things like "scope", "context", "namespace", and "hierarchy" all lend themselves to being a query parameter. This makes #2 palatable despite your reservation.

    This seems like a case of KISS. REST doesn't specifically cover this case.