Ruby on Rails | RESTful API 생성 및 사용

GEUNNN Lee·2021년 4월 18일
0

RESTful API

  • RESTful: 경로와 메소드 만으로 어떤 행위를 하는건지 알 수 있는 것
  • RESTful API: RESTful 규칙으로 만들어진 api
  • controller: 경로에 들어왔을 때 프론트 단에 적합한 상품을 뿌려줘야하는데 그 작업을 하는게 controller
#routes.rb 파일
Rails.application.routes.draw db
	get '/items' => 'items#index'
	#get으로 들어왔을 때는 items에 있는 index로 가라
	post 'items' => 'items#create'
	#post로 들어왔을 때는 items에 create로 가라
	
	resources :items, shallow: true, except: [:index, :show] do
		resources :options
	end
end

=begin
- 위처럼 해도 되지만 resources :items(api 주소)를 이용하면
모든 메소드들이 다 적혀있고 이를 활용하면 됨
- 특정 메소드만 필요할 떄는 only: []를 사용
- 특정 메소드가 필요 없는 경우는 excepnt: []를 사용
- do, end로 감싸서 아이템의 특정 부분에 대해서도 확인 가능
- shallow: 아이템 id가 필요없는 경우에 사용, update/destroy에서 아이템 아이디 없이 사용
	특정 옵션을 삭제하고 싶은데 그럴 때는 아이디를 알 필요가 없음, 옵션의 아이디만 알아도 가능
=end
rails routes|grep items
#api 주소를 확인하고 싶을 때 사용
#custom 주소도 사용 가능
Rails.application.routes.draw db	
	resources :items, shallow: true, except: [:index, :show] do
		resources :options
	
		#단순한 구조일 경우
		collection do
			get :hello
		end

		#특정 id 값이 필요한 경우
		member do
			get :hello
		end
	end
end

API로 로그인 하기

  • redis 이용해 확인
brew install redis

#redis 서버 실행
redis-server

#redis 클라이언트로 접속 (서버가 켜진 상태에서)
redis-cli

#모든 키 조회
keys *
  • postman으로 header에 csrf와 토큰을 넣어서 요청을 보냄

Serializer

  • 데이터를 직렬화
rails g api items
#items api 생성
def each_serialize
end

#여러개 activerecord relation을 보낼 때 (ex. Items.all)

def serialize
end
#한 개의 activerecord relation을 보낼 때
  • 디버깅을 하기 쉽게 만들어진 것: byebug
def create
	byebug
end

=begin
이렇게 우선 레일즈에서 짜고 postman으로 request를 보내면 터미널에서
어떻게 넘어왔는지 볼 수 있음
=end

Item.create(params.permit(:name, :price))
Item.create(params.require(:item).permit(:name, :price))
profile
Frontend Developer 👩🏻‍💻👩‍💻

0개의 댓글