Search code examples
apiresturlrestful-urlrestful-architecture

RESTful API with multitenancy and shared resources


I am trying to figure out the "right" implementation for an url structure for an application with multitenancy support and shared resources.

Resources: Users, Projects

The URL schema is

host/api/tenant_id/resource[/id][/subresource][/id]

User A (width id = 1) gets a collection of his projects at

GET http://example.com/api/1/projects/

User A creates a new project, readable by

GET http://example.com/api/1/projects/2

Now User A gives another User B (id = 2) access to project 2. User B would like to see a collection of all projects related to his account via:

GET http://example.com/api/2/projects/

Should the shared project (id = 2) be in this collection besides those, User B created by himself? Or is there a better naming structure for shared resources?


Solution

  • Focusing on the design of URL structures is actually a no-go for RESTful architectures. Roy Fielding:

    A REST API must not define fixed resource names or hierarchies (an obvious coupling of client and server).

    See also this answer.

    For your specific problem I would return a list of (basically arbitrary) hypertext links to the projects the user has access to. The links would contain attributes making it clear, whether the project is »owned« or »accessible« by the user. To improve readability you could design your resource URLs as

    http://example.com/user/{user id}
    http://example.com/project/{project id}
    

    The representation of user after a GET http://example.com/user/2 would contain the list of links like

    <a href="http://example.com/project/1" class="owned"/>
    <a href="http://example.com/project/2" class="access-permitted"/>
    

    The HATEOAS principle is inherent to REST and makes most »how do I design my URIs« questions obsolete:

    The principle is that a client interacts with a network application entirely through hypermedia provided dynamically by application servers. A REST client needs no prior knowledge about how to interact with any particular application or server beyond a generic understanding of hypermedia.