rails 做api接口入门说明
一、创建一个新的api
rails new my_api --api
这会做三件事:
- 用更少的中间件配置你的应用程序,尤其不包含相关浏览器应用程序的东西。
ApplicationController继承ActionController::API而不是继承ActionController::Base。- 它不会产生views、helpers和assets。
二、使用缓存中间件
def show @post = Post.find(params[:id]) if stale?(last_modified: @post.updated_at, public: true) render json: @post endendstale?会缓存一个url的最新修改内容。如果内容没有变,就会返回“304 Not Modified”。
三、使用 Rack::Sendfile
当你在controller里使用发送文件方法时,它会把header设置为
X-Sendfile。Rack::Sendfile来负责发送文件。 下面的配置可以加速文件发送:
# Apache and lighttpd
config.action_dispatch.x_sendfile_header = "X-Sendfile" # Nginx config.action_dispatch.x_sendfile_header = "X-Accel-Redirect"四、使用ActionDispatch::Request
它可以解析json格式的参数。
参考:http://guides.rubyonrails.org/api_app.html
浙公网安备 33010602011771号