I am creating some APIs using apiary, so the language used is JSON.
Let's assume I need to represent this resource:
{
"id" : 9,
"name" : "test",
"customer_id" : 12,
"user_id" : 1,
"store_id" : 3,
"notes" : "Lorem ipsum example long text"
}
Is it correct to refer to other resources by their IDs (12
, 1
, 3
), or I should specify the URL of these resources (i.e. /customers/12
, /users/1
, /stores/3
)?
I am not using HATEOAS and I am a bit confused.
DO include absolute entity URIs in your responses (such as
/customers/12
or evenhttp://www.example.com/customers/12
).DO NOT include just an entity's ID (such as
12
) in a response, because that way you're forcing clients to put together resource URIs themselves. In order to do that, they would need to have prior knowledge of what URIs there are, and you're losing control over the URI space on the server side.(Having the client put together an URI is OK if the server instructs the client how, e.g. by sending a URI template along with the ID; but if it did that, it could just as well send the resulting URI.)
See also:
HAL, which specifies a standard way to put links to related resources into your responses.
JSON API — "a specification for building APIs in JSON"
The above advice is not just for IDs of other resources (i.e. "foreign keys" such as your
customer_id
); you'd also turn the resource's ownid
into a so-called "self link"; see the SO question "What is the importance of the self link in hypermedia APIs?".Example:
Your original resource could be re-designed as follows:
A few things to note:
type
,id
,links
.type
might seem somewhat redudant; often, you implicitly know what kind of object to expect. This property can help in validation, and also gives you the opportunity to distinguish between object type and role (e.g.cashier
is-auser
in the above example).