views:

76

answers:

3

I'm having a bit of difficulty coming up with the right answer to this, so I will solicit my problem here. I'm working on a RESTFul API. Naturally, I have multiple resources, some of which consist of parent to child relationships, some of which are stand alone resources. Where I'm having a bit of difficulty is figuring out how to make things easier for the folks who will be building clients against my API.

The situation is this. Hypothetically I have a 'Street' resource. Each street has multiple homes. So Street :has_many to Homes and Homes :belongs_to Street. If a user wants to request an HTTP GET on a specific home resource, the following should work:

http://mymap/streets/5/homes/10

That allows a user to get information for a home with the id 10. Straight forward. My question is, am I breaking the rules of the book by giving the user access to:

http://mymap/homes/10

Technically that home resource exists on its own without the street. It makes sense that it exists as its own entity without an encapsulating street, even though business logic says otherwise.

What's the best way to handle this?

EDIT! In spirit of becoming a good StackOverflow citizen, I've come back with a supported code block for how to implement they above.

map.resources :streets,
              :has_many => :homes
              :shallow => true

This will create both types of routes that I was looking for.

+3  A: 

If your Home records can only belong to one Street, then the relationship won't be confused when you're examining a Home individually. You'll still be able to back-track to the associated Street record for whatever reason.

It's in situations where you have a many-to-many relationship that de-nesting your REST structure can get you into trouble. If a particular record only makes sense in a particular context, and you remove that context, obviously there is confusion.

I think in your particular case you may not need to implement both approaches, but instead go with the "flatter" approach that reduces the complexity of the URL.

tadman
If you _do_ offer both options, you'll want to be sure to use `rel="canonical"` on one of them to link to the other. (Probably link _from_ the deeper _to_ the shallower version.)
James A. Rosen
A: 

Nope, that is how shallow routes work and are used a lot.

nightshade427
A: 

I really like this approach. I recomend to read it. In short this article says that you shouldn't nest your resources more then 1 level. And if it is possible that nested resource can be shallowed, then do it.

In one of my applications I really messed things up with nested resources. I go even to 3 or 4 deep and it become a nightmare...

Nesting is really nice if it makes things simpler. If not, give it up!

klew