简体   繁体   中英

Rails API render all responses in camelCase

I'm trying to get my Rails API to render all JSON responses in camelCase. Currently I am using Netflix Fast JSON API for my serializer and rendering errors like so:

render json: { errors: command.errors }, status: :unauthorized

For the Netflix Fast JSON API serializers I've been adding set_key_transform :camel_lower to every serializer, which seems to do the trick (although if anyone knows how to make that a default it would be much appreciated).

For rendering errors however I'm not sure the best way to go about camel casing. If anyone has any experience with this please let me know how you go about it! Ideally there is a method of doing this that doesn't add too much syntax to every render call being made.

UPDATE

In serializing errors I added a helper method on the application controller:

def render_error(errors_params, status)
  render json: {
    errors: errors_params
  }.deep_transform_keys { |key| key.to_s.camelize(:lower) }, status: status
end

For the Netflix Fast JSON API I took the suggestion of @spickermann and added an application serializer for the other serializers to inherit from:

class ApplicationSerializer
  include FastJsonapi::ObjectSerializer
  set_key_transform :camel_lower
end
class SomeSerializer < ApplicationSerializer
  attributes :attribute, :other_attribute
end

You could create an ApplicationSerializer and all other serializers could inherit from it:

class ApplicationSerializer
  include FastJsonapi::ObjectSerializer
  set_key_transform :camel_lower
end

class FooBarSerializer < ApplicationSerializer
  attributes :buzz, :fizz 
  # ...
end

You could monkey patch the serializer

Rails.application.config.to_prepare do
  FastJsonapi::ObjectSerializer.class_eval do
    set_key_transform :camel_lower
  end
end

and for handling errors you can probably create an error serializer

render serializer: ErrorSerializer, json: {status: : unauthorized, errors: resource.errors 

Have a look here and here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM