Skip to content

Instantly share code, notes, and snippets.

@nadnoslen
Last active February 1, 2017 17:12
Show Gist options
  • Save nadnoslen/70c31de2a5ed88c73a4c72a2aa0d0f1e to your computer and use it in GitHub Desktop.
Save nadnoslen/70c31de2a5ed88c73a4c72a2aa0d0f1e to your computer and use it in GitHub Desktop.

Creating Customized JSONAPI Compliant Responses

There are times when using jsonapi-resources that you will need to write your own controller actions because you have complicated logic or a resource with relationships to process in a single transactioned request. It's nice to know how to handle the success and failure responses in a JSONAPI compliant manner. Thankfully jsonapi-resources exposes these features to us, you just need to read some code to figure out how to use them.

A Typical Success Response

Consider a use-case where you are updating a Users model and its collection of assigned Roles. Say you author an action in your users_controller.rb named update_user_and_roles:

def update_user_and_roles
  # ... process write your logic to process the `User` model and the `Role` models...that's outside the scope of this example
  # render the updated User model in the JSONAPI compliant way
  render status: :ok, json: JSONAPI::ResourceSerializer
    .new(UserResource, include: ['roles'])
    .serialize_to_hash(UserResource.new(user, context))
end

A Typical Unprocessible Entity Response

Consider the same update_user_and_roles example. Perhaps the User model failed some of its validations and the errors collection needs to be sent back to the caller in a JSON compliant manner:

def update_user_and_roles
  # ... process write your logic to process the `User` model and the `Role` models...that's outside the scope of this example
  # render the User model's errors in the JSONAPI compliant way
  render status: :unprocessable_entity, json: { 
    errors: JSONAPI::Exceptions::ValidationErrors.new(User.new(user, context)).errors
  }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment