Creating Rails APIs in JSON

suggest change

This example assumes that you have experience in creating Rails applications.

To create an API-only app in Rails 5, run

rails new name-of-app --api

Add active_model_serializers to the Gemfile:

gem 'active_model_serializers'

install bundle in terminal

bundle install

Set the ActiveModelSerializer adapter to use :json_api

# config/initializers/active_model_serializers.rb
ActiveModelSerializers.config.adapter = :json_api

# Do not re-register :json. Add the JSON:API media type on its own.
Mime::Type.register "application/vnd.api+json", :jsonapi

Generate a new scaffold for your resource

rails generate scaffold Task name:string description:text

The scaffold generates files such as:

Controller: app/controllers/tasks_controller.rb
Test:       test/models/task_test.rb
            test/controllers/tasks_controller_test.rb
Routes:     resources :tasks added in config/routes.rb
Migration:  db/migrate/YYYYMMDDHHMMSS_create_tasks.rb
Model:      app/models/task.rb
Serializer: app/serializers/task_serializer.rb

An --api app skips views and helpers. The serializer is generated only when active_model_serializers is loaded.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents