1) How to work with relationships?
Let’s say I’ve an Article resource, which is written by an Author.
Basically I’ll have something like :
{
"article": {
"id": 1,
"title": "Foo bar",
"body": "Lorem ipsum dolor sid amet",
"published_on": "2011-05-06 21:54:23",
"author": {
"id": 25,
"username": "johndoe"
}
}
}
I’ll access my resource at api/articles/1
My question is, what is the best way to represent this data?
Should I do something like:
{
"article": {
"id": 1,
"title": "Foo bar",
"body": "Lorem ipsum dolor sid amet",
"published_on": "2011-05-06 21:54:23",
}
}
And access author by calling api/articles/1/author
Only include author id (subobject identifier)
{
"article": {
"id": 1,
"title": "Foo bar",
"body": "Lorem ipsum dolor sid amet",
"published_on": "2011-05-06 21:54:23",
"author": {
"id": 25,
}
}
}
Or including the full relationship as seen above?
2) PUT or POST to create new object?
Looking on SO and elsewhere, I’ve noted that both are used to create and/or update object.
As far as I understand, both are valid action but it depends on the context. If I create a subobject related to a previously created object I’ve to use POST.
Ex: I create a vote for an article, as the Article already exists, I’ll POST a new vote, however, if I create a new Article, I PUT it.
Am I right?
3) How should we format Date?
I’ve seen that SO use Unix Timestamp, where ISO8601 are mostly used elsewhere.
Is there any “standard” or recommandation about this?
Your first approach isn’t very good because it does not allow to discover the author – probably something you want to know.
The second approach is valid, but requires you to know the URI pattern to lazily fetch author in advance, e.g.
api/author/25.Third approach is fine as long as you don’t have one-to-many relationships (the size of the document grows exponentially) or very large nested objects.
The fourht approach, advocated by several people, is to employ hateos principle by using hyperlinks rather than abstract identifiers or full documents.
There is no confusion here. POST is always used to create new object while PUT should update existing one (or possibly create one if it doesn’t exist. Bottom line: every time you call POST, you change the state of the system (resource). However you can call PUT multiple times (idempotency – great when you want to safely retry).
Note that POST links typically do not contain ids (e.g.
POST api/articles) while PUT DO:PUT api/articles/42. If you know the ID, the entity probably already exists.Both UNIX timestamps and iso8601 are fine. I am not sure if there is any standard appart from JSON schema recommendations: