중고 신입이 개발해보기..

Rails] Simple Ruby On Rails REST API 본문

Back-End /Ruby On Rails

Rails] Simple Ruby On Rails REST API

rootkaien 2019. 10. 2. 11:36

참고 채널 : https://youtu.be/QojnRc7SS9o

ㄴ 유투브중에 간단하게 API를 만드는 방법이 나와서 따라하기 진행~~

 

현재 Rails 6를 사용중.. 

 

* 모델 생성 

 

$ ./bin/rails g model Article title:string body:string 

 

class CreateArticles < ActiveRecord::Migration[6.0]
  def change
    create_table :articles do |t|
      t.string :title
      t.text :body
      t.timestamps
    end
  end
end

모델에 데이터를 입력해주기 위해서 faker 설치 

( https://github.com/faker-ruby/faker )

group :development do
  gem 'faker', :git => 'https://github.com/faker-ruby/faker.git', :branch => 'master'
end

db/seeds.rb 에 추가 

30.times do
  Article.create({
      title: Faker::Book.title,
      body: Faker::Lorem.sentence
  })
end

$ ./bin/rails db:seed 

ㄴ 디비에 임의의 데이터가 입력된다~!!

 

파일 생성 

 

$ vi app/controllers/api/v1/articles_controller.rb 

module Api
  module V1
    class ArticlesController < ApplicationController
      def index
        articles = Article.order('created_at DESC')
        render json: { status: 'SUCESS', message: 'Loaded articles', data: articles }, status: :ok
      end

      def show
        article = Article.find(params[:id])
        render json: { status: 'SUCESS', message: 'Loaded article', data: article }, status: :ok
      end
    end
  end
end

$ vi config/routes.rb 

  namespace 'api' do
    namespace 'v1' do
      resources :articles
    end
  end

 

 

Postman을 이용한 api확인 

index 시 
show 시 

 

 

post create 를 추가해봄 

module Api
  module V1
    class ArticlesController < ApplicationController
      skip_before_action :verify_authenticity_token

      def index
        articles = Article.order('created_at DESC')
        render json: { status: 'SUCESS', message: 'Loaded articles', data: articles }, status: :ok
      end

      def show
        article = Article.find(params[:id])
        render json: { status: 'SUCESS', message: 'Loaded article', data: article }, status: :ok
      end

      def create
        article = Article.new(article_params)

        if article.save
          render json: { status: 'SUCESS', message: 'Saved article', data: article }, status: :ok
        else
          render json: { status: 'ERROR', message: 'Article not Saved', data: article.errors }, status: :unprocessable_entity
        end
      end

      private

      def article_params
        params.permit(:title, :body)
      end
    end
  end
end

Can't verify CSRF token authenticity. 오류가발생 

skip_before_action :verify_authenticity_token 추가해서 일단 오류를 막아봄.. 

 

header에 

ㄴ key - Content-Type

ㄴ value - application/json 으로 

Body는 

ㄴ row 

 

추가된다~!!

 

      def destroy
        article = Article.find(params[:id])
        article.destroy
        render json: { status: 'SUCESS', message: 'Deleted article', data: article }, status: :ok
      end

 

 

삭제가 된다~!!

 

Update 추가 

 

      def update
        article = Article.find(params[:id])
        if article.update_attributes(article_params)
          render json: { status: 'SUCESS', message: 'Updated article', data: article }, status: :ok
        else
          render json: { status: 'ERROR', message: 'Article not Updated', data: article.errors }, status: :unprocessable_entity
        end
      end

 

 

 

 

완성된.. 심플 api 코드 

module Api
  module V1
    class ArticlesController < ApplicationController
      skip_before_action :verify_authenticity_token
      before_action :article_find, only: [:show, :destroy, :update]

      def index
        articles = Article.order('created_at DESC')
        render json: { status: 'SUCESS', message: 'Loaded articles', data: articles }, status: :ok
      end

      def show
        render json: { status: 'SUCESS', message: 'Loaded article', data: @article }, status: :ok
      end

      def create
        article = Article.new(article_params)

        if article.save
          render json: { status: 'SUCESS', message: 'Saved article', data: article }, status: :ok
        else
          render json: { status: 'ERROR', message: 'Article not Saved', data: article.errors }, status: :unprocessable_entity
        end
      end

      def destroy
        @article.destroy
        render json: { status: 'SUCESS', message: 'Deleted article', data: @article }, status: :ok
      end

      def update
        if @article.update_attributes(article_params)
          render json: { status: 'SUCESS', message: 'Updated article', data: @article }, status: :ok
        else
          render json: { status: 'ERROR', message: 'Article not Updated', data: article.errors }, status: :unprocessable_entity
        end
      end

      private

      def article_params
        params.require(:article).permit(:title, :body)
      end

      def article_find
        @article = Article.find(params[:id])
      end
    end
  end
end
Comments