Dragon Arrow written by Tatsuya Nakaji, all rights reserved animated-dragon-image-0164

Rails5.2でAPIを作る

Mar 22, 2019

Rails5.2 APIで認証付きのWebAPIを作ってみる

はじめに

Rails5.2

使用ソフトウェアのバージョン情報

Rails5.2


こちらの記事がかなり助かりました。

https://qiita.com/ochiochi/items/966b884eb17045dfb929


APIの応答はrenderをいじれば良い

class LoginController < ApplicationController
def login
  login_user = User.find_by(user_id:params[:user_id], password:params[:password])
  if login_user != nil
    render json: {"message": "User details by user_id", "user": {
      "id": login_user.id, "user_id": login_user.user_id, "nickname": login_user.nickname, "comment": login_user.comment}
    }
  else
    render plain: 'no auth'
  end
end
end
class UsersController < ApplicationController
before_action :set_user, only: [:show, :update, :destroy]

# GET /users
def index
@users = User.all

render json: @users
end

# GET /users/1
def show
render json: @user
end

# POST /users
def create
@user = User.new(user_params)

if @user.save
render json: {"message": "Account successfully created", "user": {
"user_id": @user.user_id}
}, status: :created, location: @user
else
render json: @user.errors, status: :unprocessable_entity
end
end

# PATCH/PUT /users/1
def update
if @user.update(user_params)
render json: @user
else
render json: @user.errors, status: :unprocessable_entity
end
end

# DELETE /users/1
def destroy
@user.destroy
end

private
# Use callbacks to share common setup or constraints between actions.
def set_user
@user = User.find(params[:id])
end

# Only allow a trusted parameter "white list" through.
def user_params
params.require(:user).permit(:user_id, :password, :token, :comment, :nickname)
end
end


ROUTEは好きに変更

Rails.application.routes.draw do
post '/login' => 'login#login'
post '/signup' => 'users#create'
delete '/users/:id' => 'users#destroy'
post '/users/:id/closed' => 'users#destroy'
resources :users
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end


モデルのバリデーション

class User < ApplicationRecord
has_secure_token

validates :user_id, length: { in: 6..20 } # 「8文字以上20文字以下」
validates :password, length: { in: 8..20 } # 「8文字以上20文字以下」

end


that's all.