Creating a JSON API in Rails

By Nick Rodriguez

Add the ActiveModelSerializers gem to your Gemfile.

rails_api_gems.PNG
./Gemfile

Expose the desired API endpoints. If we want to expose a lot of data, we can use a controller wildcard. 

rails_api_routes.PNG
./config/routes.rb

Since this will match some paths that we don't want to expose or aren't valid routes (e.g. /sessions/1/data), and since all our controllers inherit from ApplicationController, we can add some default behavior to keep things safe.

rails_api_controller_application.PNG
Redirect to root by default

Now we can override the default action in our respective controllers, as well as add two additional actions in our users controller.

rails_api_controller_users.PNG
Override default behavior, render requested data

Rails already has an instance.to_json method via ActiveRecord::Serialization, but the Serializers gem we added allows us to define our own custom serializers. This way, we can serve exactly the data we want through our API, rather than ALL the model's data.

rails_api_serializer_user.PNG
./serializers/user_serializer.rb

Serializers are defined very similarly to Models, and ActiveModelSerializers automatically nests associated models one level deep. Additionally we can define custom attributes to send with our data. 

rails_api_serializer_review.PNG
./serializers/review_serializer.rb

In this case a Review does not have a medium_title attribute, but when accessing review data via our API, we'll need to know which medium was reviewed. Note that object, in our medium_title accessor, is the current object being serialized.

rails_api_serializer_view.PNG
./serializers/view_serializer.rb

Similarly the View does not have a title attribute, but it is useful to know when it is accessed via the API. 

Now this data is readily available at our specified endpoints.

rails_api_response_user.PNG
GET /users/1/data

rails_api_response_user_reviews.PNG
GET /users/1/reviews

rails_api_response_user_views.PNG
GET /users/1/views

View the source on GitHub.


  Ruby on Rails Web App pt 2 - Routing|Consuming your Rails API with React/Redux