I'm updating a RESTful API and it's already using JSON API.
I want to enable POSTs to /quotes
, but quotes are required to have a product
.
My question is: how should the client know about, and identify, the product that should be associated with the quote?
Here are a few ideas; I welcome others.
/products
first, find the desired product in the list returned, then send the id
of the product in question."acme_1"
, etc. As for option 2, the code could either be sent in as an attribute
or as a relationship
. That is, we could either do
// option 2a
"data": {
"type": "accounts",
"attributes": {
"foo": "bar",
"product_code": "acme_1"
}
}
// option 2b
"data": {
"type": "accounts",
"attributes": {
"foo": "bar"
}
relationships: {
"type": "products",
"id": "acme_1"
}
}
Please send thoughts, suggestions, and/or reading suggestions!
If you have a one-to-many relationship between quote
and product
this should be reflected in your payload. A relationship must be in relationships
key of a resource object. A resource linkage
must be under data
key of a relationships object
. Therefore both of your options presented as 2a and 2b are not compliant with spec. A valid payload to create a resource having a relationship would look like the following:
{
"data": {
"type": "accounts",
"attributes": {
"foo": "bar"
}
relationships: {
"product": {
"data": {
"type": "products",
"id": "acme_1"
}
}
}
}
}
Please note that the example shows a relationship object for a one-to relationship. If an account could have many product data
property of
relationship object must be an array:
{
"data": {
"type": "accounts",
"attributes": {
"foo": "bar"
}
relationships: {
"product": {
"data": [
{
"type": "products",
"id": "acme_1"
},
{
"type": "products",
"id": "acme_2"
},
]
}
}
}
}
From perspective of JSON API spec it does not matter how the client knows which ID to associate. The spec only states that an id
must be a string and that the combination of type
and id
"must identify a single, unique resource".
Of course the client must know to which resource should be associated with the created one. It's totally up to the application how to implement that one. It could be hard coded or fetched from the backend. For scalability and maintainability reasons I would recommend not to hard code it if there is any chance that it's changing on a regular basis. But from JSON API spec perspective it only matters if the referenced related resource exists. Otherwise the server must return a 404 Not Found
.