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数据流;

转载于:https://www.cnblogs.com/lv-books/p/6479158.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值