I wasn't sure what API communication was doing at first. This time, so that people with the same problems can have an image as much as possible. I will introduce an implementation that returns the response result after execution in JSON without creating a UI. The subject is sign-up and login, which Rails beginners probably learned first.
routes.rb
Rails.application.routes.draw do
#In namespace/api/v1/Create a hierarchy of
namespace :api, format: :json do
namespace :v1 do
post :sign_up, to: 'users#sign_up'
post :login, to: 'users#login'
end
end
end
users_controller.rb
class Api::V1::UsersController < ApplicationController ##Match class name to hierarchy
def sign_up
user = User.new(user_params)
if user.save
render status: "200", json: { result: user } #Return user information in json format when saving is successful
else
render status: "400", json: { result: "Email address or password is not valid" }
end
end
def login
user = User.find_by(email: params[:email])
if user && user.authenticate(params[:password])
render status: "200", json: { result: user } #Return user information in json format when login is successful
else
render status: "400", json: { result: "Email address or password do not match" }
end
end
private
def user_params
params.permit(:email, :password)
end
end
After installing (https://www.postman.com/), please try as shown in the image. After setting, click the "Send" button to execute!
You can easily limit it using as_json. Reference URL https://qiita.com/tbaba/items/ea44025b056f708ab0b4
Once I knew it, it was surprisingly easy. But beginners take time to know this. .. .. I hope it helps someone.
Recommended Posts