Skip to content

Instantly share code, notes, and snippets.

@juandazapata
Last active December 12, 2015 05:38
Show Gist options
  • Save juandazapata/4722842 to your computer and use it in GitHub Desktop.
Save juandazapata/4722842 to your computer and use it in GitHub Desktop.
JSON Conventions

URL Conventions

ActionHTTP VerbURL
FindGET/people/123
Find AllGET/people
UpdatePUT/people/123
CreatePOST/people
DeleteDELETE/people/123

JSON Conventions

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.

JSON Root

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"
  }
}

Underscored Attribute Names

All the JSON attributes should be underscored.

{
  "person": {
    "first_name": "Juanda",
    "last_name": "Zapata",
    "is_admin": true
  }
}

Relationships

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
  }
}

Response status

Create/update

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

Delete

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment