ruby 構建API接口流程代碼


來源:https://ruby-china.org/topics/25822

1、創建新項目

  rails new api_demo

2、生成控制器:

  # 我們不需要生成資源文件   $ bundle exe rails g controller api/v1/base --no-assets 

  app/controllers/api/v1/base_controller.rb,

  class Api::V1::BaseController < ApplicationController    # disable the CSRF token    protect_from_forgery with: :null_session    # disable cookies (no set-cookies header in response)    before_action :destroy_session   # disable the CSRF token    skip_before_action :verify_authenticity_token       def destroy_session    request.session_options[:skip] = true   end   end
3、配置路由

  config/routes.rb,

  namespace :api do    namespace :v1 do    resources :users, only: [:index, :create, :show, :update, :destroy]    # 原文有 microposts, 我們現在把它注釋掉    # resources :microposts, only: [:index, :create, :show, :update, :destroy]    end   end
4、
生成控制器:
  # 我們不需要生成資源文件   $ bundle exe rails g controller api/v1/users --no-assets 

  app/controllers/api/v1/users_controller.rb,

  class Api::V1::UsersController < Api::V1::BaseController    def show    @user = User.find(params[:id])    # 原文使用 Api::V1::UserSerializer    # 我們現在使用 app/views/api/v1/users/show.json.jbuilder    # render(json: Api::V1::UserSerializer.new(user).to_json)    end   end 

  app/views/api/v1/users/show.json.jbuilder,

  json.user do    json.(@user, :id, :email, :name, :activated, :admin, :created_at, :updated_at)   end
5、
User 模型和 users 表
  $ bundle exe rails g model User 

  app/models/user.rb,

  class User < ActiveRecord::Base   end 

  db/migrate/20150502072954_create_users.rb,

  class CreateUsers < ActiveRecord::Migration    def change    create_table :users do |t|    t.string :email    t.string :name    t.datetime :activated    t.boolean :admin, default: false    t.timestamps null: false    end   end   end 
6、
數據遷移:
  $ bundle exe rake db:migrate 

  種子數據:

  db/seeds.rb,

  users = User.create([    {    email: 'test-user-00@mail.com',    name: 'test-user-00',    activated: DateTime.now,    admin: false    },    {    email: 'test-user-01@mail.com',    name: 'test-user-01',    activated: DateTime.now,    admin: false    }    ]) 

  創建種子數據:

  $ bundle exe rake db:seed
7、
現在我們可以測試一下 api 是否正常工作, 我們可以先查看下相關 api 的路由,
$ bundle exe rake routes 

輸出:

      Prefix Verb URI Pattern Controller#Action api_v1_users GET /api/v1/users(.:format) api/v1/users#index POST /api/v1/users(.:format) api/v1/users#create api_v1_user GET /api/v1/users/:id(.:format) api/v1/users#show PATCH /api/v1/users/:id(.:format) api/v1/users#update PUT /api/v1/users/:id(.:format) api/v1/users#update DELETE /api/v1/users/:id(.:format) api/v1/users#destroy 

啟動 rails 服務,

$ bundle exe rails s 

使用 curl 請求 api,

$ curl -i http://localhost:3000/api/v1/users/1.json 
   
1、增加認證(Authentication)

  認證的過程是這樣的: 用戶把她的用戶名和密碼通過 HTTP POST 請求發送到我們的 API (在這里我們使用 sessions 端點來處理這個請求), 如果用戶名和密碼匹配,我們 會把 token 發送給用戶。 這個 token 就是用來證明用戶身份的憑證。然后在以后的每個請求中,我們都通過這個 token 來查找用戶,如果沒有找到用戶則返回 401 錯誤。

2、給 User 模型增加 authentication_token 屬性
  $ bundle exe rails g migration add_authentication_token_to_users 

  db/migrate/20150502123451_add_authentication_token_to_users.rb

  class AddAuthenticationTokenToUsers < ActiveRecord::Migration    def change    add_column :users, :authentication_token, :string    end   end 
  $ bundle exe rake db:migrate 

3、生成 authentication_token

  app/models/user.rb,

  class User < ActiveRecord::Base    before_create :generate_authentication_token    def generate_authentication_token    loop do     self.authentication_token = SecureRandom.base64(64)      break if !User.find_by(authentication_token: authentication_token)     end    end    def reset_auth_token!     generate_authentication_token     save    end   end 
最后注意的是:rails 5 中就可以棄用 gem 'jbuilder',這樣就可以不必創建views文件,直接在apicontroller中直接render json數據流;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM