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

ruby 构建API接口流程代码的更多相关文章

  1. 面向对象的全套“企业微信”api接口的代码实现,网上太多“面向过程”微信api接口的代码,这个开源给需要的人用

    有段时间没有写文章了. 一直以来,微信的热门是看得到的,很多人都需要与微信的api对接. 今天我这里就分享全套的企业微信api接口的代码. 关于微信api,网上已经有很多实现的了. 但是我今天之所以还 ...

  2. ASP.NET WebAPI构建API接口服务实战演练

    一.课程介绍 一.王小二和他领导的第一次故事 有一天王小二和往常一下去上早班,刚吃完早餐刚一打开电脑没一会儿.王小二的领导宋大宝走到他的面前,我们现在的系统需要提供服务给其他内部业务系统,我看你平时喜 ...

  3. ASP.NET Core WebApi构建API接口服务实战演练

    一.ASP.NET Core WebApi课程介绍 人生苦短,我用.NET Core!提到Api接口,一般会想到以前用到的WebService和WCF服务,这三个技术都是用来创建服务接口,只不过Web ...

  4. 文华财经赢顺外盘期货行情数据API接口开放代码

    文华财经赢顺外盘期货行情数据API接口开放代码        怎么才能获取到外盘期货行情数据API接口呢?不少朋友就会考虑到文华财经行情API接口,本身文华财经就是一个软件提供商,提供行情API接口也 ...

  5. 手把手教你用Abp vnext构建API接口服务

    ABP是一个开源应用程序框架,该项目是ASP.NET Boilerplate Web应用程序框架的下一代,专注于基于ASP.NET Core的Web应用程序开发,也支持开发控制台应用程序. 官方网站: ...

  6. 使用Swoole 构建API接口服务

    网上类似的文章已经很多了,我也是刚入门.从头开始学习.所以如果重复写文章阐释,反而会浪费时间,于是就自己动手构建了一个demo,使用swoole 的TCP 服务器接受TCP客户端的发来的http请求, ...

  7. 快递鸟API接口调用代码示例(免费不限量)

    import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import ...

  8. php 登录注册api接口代码

    /** *一览(www.yl1001.com) * PHP开发API接口 服务端 */ require 'conn.php'; //连接数据库的文件 header('Content-Type:text ...

  9. 构建标准OpenStack API接口文档

    1.构建API接口文档标准参考: http://docs.openstack.org/contributor-guide/api-guides.html 2.构建API接口文档步骤参考下面的Patch ...

随机推荐

  1. jenkins手把手教你从入门到放弃03-安装Jenkins时web界面出现该jenkins实例似乎已离线

    简介 很久没有安装jenkins了,因为之前用的的服务器一直正常使用,令人郁闷的是,之前用jenkins一直没出过这个问题. 令人更郁闷的是,我尝试了好多个历史版本和最新版本,甚至从之前的服务器把je ...

  2. hdu 2554 最短路 (dijkstra)

    最短路Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submissi ...

  3. nyoj 975-关于521 (EOF)

    975-关于521 内存限制:64MB 时间限制:1000ms 特判: No 通过数:5 提交数:46 难度:2 题目描述: Acm队的流年对数学的研究不是很透彻,但是固执的他还是想一头扎进去. 浏览 ...

  4. 领扣(LeetCode)回文链表 个人题解

    请判断一个链表是否为回文链表. 示例 1: 输入: 1->2 输出: false 示例 2: 输入: 1->2->2->1 输出: true 进阶:你能否用 O(n) 时间复杂 ...

  5. 实现websocket 主动消息推送,用laravel+Swoole

    近来有个需求:想实现一个可以主动触发消息推送的功能,这个可以实现向模板消息那个,给予所有成员发送自定义消息,而不需要通过客户端发送消息,服务端上message中监听传送的消息进行做相对于的业务逻辑. ...

  6. Linux\Nginx 虚拟域名配置及测试验证

    使用 Nginx 虚拟域名配置,可以不用去购买域名,就可以通过特定的域名访问本地服务器.减少发布前不必要的开支. 配置步骤 1. 编辑 nginx.conf 配置文件 sudo vim /usr/lo ...

  7. PHP创建对象的6种方式

    创建对象实例: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 ...

  8. node 后台使用增删改查(4)

    无论node还是java增删改查都是一样的原理,变得是配合框架使用时候有简便方法而已. 这里我接着上一篇开始讲,使用同一个数据库(数据库创建)这里必须创建了数据库 优化:为了维护方便这里我们把sql语 ...

  9. 【Luogu P1981】表达式求值

    点我进入原题Luogu P1981 [解题思路] 仔细分析题目,这就是一道模拟题…… 直接按照符号读入全部的数字,先算乘法,最后把全部数加起来就是结果了 记得要%10000取最后四位 [参考程序] # ...

  10. linuxLVM之LV扩大和缩小容量(非xfs文件系统)

    LVM的基础请见:https://www.cnblogs.com/wxxjianchi/p/9698089.html 一.放大LV的容量.放大容量是由内而外来操作的. 1.设置新的lvm分区:用fdi ...