ユーザー新規登録機能のAPIを作成

jsonのserializerはfast_jsonapiを使用。
user_serializer.rb

class UserSerializer
  include FastJsonapi::ObjectSerializer
  has_many :articles
  attributes :name, :email
end

article_serializer.rb

class ArticleSerializer
  include FastJsonapi::ObjectSerializer
  belongs_to :user
  attributes :title, :contents, :status
end


①ルーティングを設定。
namespace :api, format: 'json' do
  namespace :v1 do
    resource :registration, only: %i[create]
  end
end


②コントローラーを記載。
module Api
  module V1
    class RegistrationsController < BaseController
      def create
        @user = User.new(user_params)

        if @user.save
          json_string = UserSerializer.new(@user).serialized_json
          render json: json_string
        else
          render_400(nil, @user.errors.full_messages)
        end
      end

      private

      def user_params
        params.require(:user).permit(:name, :email, :password)
      end
    end
  end
end


確認

localhost:3000/api/v1/registration
名前、メール、パスワードを入力して登録。

{
    "user": {
        "name": "sample",
        "email": "sample@sample.com",
        "password": "password"
    }
}


出力結果

{
    "data": {
        "id": "1",
        "type": "user",
        "attributes": {
            "name": "sample",
            "email": "sample@sample.com"
        },
        "relationships": {
            "articles": {
                "data": []
            }
        }
    }
}