0

Let's assume that I have a resource called group with the following representation:

{
    "id": 1,
    "name": "Superheroes"
    "_links": {
        "self": {
            "href": "http://my.api.com/groups/1"
        }
    }
}

Now let's say I want to create a new person instance by POSTing to /persons/1. Which of the following should I use for the request body:

Using ID

{
    "name": "Batman",
    "groupId": 1
}

Using link

{
    "name": "Batman",
    "group": "http://my.api.com/groups/1"
}

With the first method I access the id directly either to look up the related resource or eventually store the id in the database, when I persist the person instance. But with the other method, I either have to extract the id from the URI or, follow the link to load the related resource, and then find out its id. I really don't want to store the URI in the database.

With the latter option, seeing that the server controls the structure of the URI, is it fine for me to parse the id out of the link? Following the link back to the server itself seems odd, seeing that at this point we already have access to the information directly (we just need the id).

So to sum up, which of these options is best?

  • Use the id directly.
  • Use the link, but parse out the id.
  • Use the link, but access the link to get the resource instance, and then get the id.
2

The "right" answer is dependent on your situation, but never link.

POST
{
    "name": "Batman",
    "groupId": 1
}

is fine

POST
{
    "name": "Batman",
    "groupName": "my group"
}

Could be nice for convenience.

Using a link is bad, because the link could change depending on tons of stuff (i.e. www.example.com/groups/1 or example.com/groups/1 or groups.example.com/groups/1-group-name-in-seo-friendly-format may all point at the same resource). You want to pass in something that "never" changes. ID is a good choice, but it may be cost effective to allow a name to be passed in (to reduce overall number of calls).

I would normally say make the consumer GET /groups.json and POST /users with the group id.

1
  • The link is constructed by the server, so that way the client won't ever pass in a link that is invalid. But yes, it does seem like extra work since the client could get the id of the related resource simply be following the link, and then pass that id in. – Vivin Paliath Jan 27 '15 at 19:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.