RESTful 1-N optional relationships RESTful 1-N optional relationships json json

RESTful 1-N optional relationships


If your framework forces your representation to include strange constructs like { "id":"1" } then I'd say it's time to switch framework!

More importantly, instead of worrying about adding a sub-JSONObject to your code, I would worry that the term "1" is indeed not really a hyperlink. Read up on the hypermedia constraint, or HATEOAS if you want.

What you want to pass in your POST is this:

{    "team_href" : "/teams/1",    "name":"can'tbebothered"}

so when the server sees this, it links the newly created employee with team #1 merely because it recognises the (relative) URI.


I would use a dedicated link type, I modelled it in xml-link tag, but it would map to following json:

{  ...  links:   [      {          "href" : "/teams/1",          "rel" : "team"      },      {          "href" : "/teams/2",          "rel" : "team"      }  ]}

I prefer above link style because it is more generic (you define the relationship through the rel attribute). To me the link concept is so important in HTTP REST that I dedicate an own type for it.

Beware in some cases for performance reasons (avoiding network calls to traverse linked resource) you need to inline such relationships. For that you could offer a switch to return a inlined representation /employee/123?inline=true. But only offer such gimmicks, if really necessary. I once had to do it, but implementation wasn't trivial (though my format was XML, which is more constrained by schema definitions).


REST offers the possibility to use URLs as references, too, which I find really cool. So it would look like this:

{    "team":"http://myapp.com/team/1",    "name":"Fred Bloggs",    "phone":"1234567890",    "email":"test@example.com"}

You can avoid passing nested objects, too by just supplying a

{    "team":"1",    "name":"Fred Bloggs",    "phone":"1234567890",    "email":"test@example.com"}

In that case your converter must be smart enough to figure that if the value of the team key is a string (or integer, whatever works) and not another JSON object it should be interpreted as an id.