Search code examples
resturl-routingparent-childhierarchy

What's the correct RESTful way to structure A Website's Parent/Child Views


NOTE: This is not specifically for an API.

I have three Entities: Building Unit Person

These are pure simple easy Exclusive 1:M relationships

A Person can only live in (1) unit A Unit can only exist in (1) unit The Building is essentially the parent.

Should I have URLs like:

The View mode is pretty easy

/buildings                        //Show all buildings
/buildings/[id]                   //Show one building
/buildings/[id]/units             //Show all units in a building
/buildings/[id]/units/[id]/people //Show all people in a unit

However, this seems kind of verbose. While those URLs may work for PUTS and POSTS which redirect to a GET, if I want to show all the units and people in a building, should I be using a route like buildings/[id]/details or is there some other standard convention?

Also, when I want to display a form to edit the values, is there a standard url path like buildings/[id]/edit A POST and a PUT in this case will essentially be using the same form ( but with the PUT having the fields filled out ) .


Solution

  • I think your question may attract some opinionated answers, but it'd be good to hear about other peoples' practices regarding RESTful API designs.

    You say your paths seem kind of verbose, and you may feel that way if your IDs are auto incremented integers and the only way to specify buildings, units, etc is with paths like

    buildings/1/units/4/tenants
    buildings/1/units/4/tenants/5
    

    To me these are clear interfaces. If I had to maintain your code, I'd think it's pretty obvious what's going on here. If I had to criticize something, I would say you seem to be developing in a way that allows for all or one selection. It's your design choice, though. Maybe that's exactly what you need in this case. Here are some examples that come to mind.

    update one tenant

    PUT buildings/1/units/4/tenants/2
    

    create three units

    POST buildings/2/units                 //carries message body for SQL in back end
    

    read tenants with certain criteria

    GET buildings/1/tenants?params=        //GET can't carry a message body
    

    delete tenants with certain criteria

    DELETE buildings/5/tenants?criteria=   //params needed?