Action | HTTP Verb | URL |
---|---|---|
Find | GET | /people/123 |
Find All | GET | /people |
Update | PUT | /people/123 |
Create | POST | /people |
Delete | DELETE | /people/123 |
Let's have clear conventions through the all the API payloads, by doing this, we can create a standard serializer object that can be reused in all the project, instead of serializing after each call with a different logic.
The primary record being returned should be in a named root. For
example, if you request a record from /people/123
, the response should
be nested inside a property called person
:
{
"person": {
"first_name": "Juanda",
"last_name": "Zapata"
}
}
All the JSON attributes should be underscored.
{
"person": {
"first_name": "Juanda",
"last_name": "Zapata",
"is_admin": true
}
}
References to other records should be done by ID. For example, if you
have a model with a hasMany
relationship:
The JSON should encode the relationship as an array of IDs:
{
"post": {
"comments": [1, 2, 3]
}
}
The JSON should encode the relationship as an ID to another record:
{
"comment": {
"post_id": 1
}
}
When there's an error respond with the JSON error object and add the 422
status (Unprocessable Entity
)
def create
user = User.new(params[:user])
if user.save
render json: user
else
render json: user, status: 422
end
end
When the delete
operation completes respond with 204
status (No Content
)
def destroy
user = User.find(params[:id])
if user.destroy
render json: user, status: 204
else
render json: user
end
end