Class: Grape::API

Inherits:
Object
  • Object
show all
Defined in:
lib/grape/api.rb

Overview

The API class is the primary entry point for creating Grape APIs. Users should subclass this class in order to build an API.

Class Method Summary collapse

Class Method Details

.auth(type = nil, options = {}, &block) ⇒ Object

Add an authentication type to the API. Currently only ‘:http_basic` is supported.



109
110
111
112
113
114
115
# File 'lib/grape/api.rb', line 109

def auth(type = nil, options = {}, &block)
  if type
    set(:auth, {:type => type.to_sym, :proc => block}.merge(options))
  else
    settings[:auth]
  end
end

.call(env) ⇒ Object



23
24
25
26
# File 'lib/grape/api.rb', line 23

def call(env)
  logger.info "#{env['REQUEST_METHOD']} #{env['PATH_INFO']}"
  route_set.freeze.call(env)
end

.default_format(new_format = nil) ⇒ Object

Specify the default format for the API’s serializers. Currently only ‘:json` is supported.



78
79
80
# File 'lib/grape/api.rb', line 78

def default_format(new_format = nil)
  new_format ? set(:default_format, new_format.to_sym) : settings[:default_format]
end

.delete(*paths, &block) ⇒ Object



161
# File 'lib/grape/api.rb', line 161

def delete(*paths, &block); route('DELETE', paths, &block) end

.get(*paths, &block) ⇒ Object



157
# File 'lib/grape/api.rb', line 157

def get(*paths, &block); route('GET', paths, &block) end

.head(*paths, &block) ⇒ Object



160
# File 'lib/grape/api.rb', line 160

def head(*paths, &block); route('HEAD', paths, &block) end

.helpers(&block) ⇒ Object

Add helper methods that will be accessible from any endpoint within this namespace (and child namespaces).

Examples:

Define some helpers.

class ExampleAPI < Grape::API
  helpers do
    def current_user
      User.find_by_id(params[:token])
    end
  end
end


93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/grape/api.rb', line 93

def helpers(&block)
  if block_given?
    m = settings_stack.last[:helpers] || Module.new
    m.class_eval &block
    set(:helpers, m)
  else
    m = Module.new
    settings_stack.each do |s|
      m.send :include, s[:helpers] if s[:helpers]
    end
    m
  end
end

.http_basic(options = {}, &block) ⇒ Object

Add HTTP Basic authorization to the API.

Parameters:

  • options (Hash) (defaults to: {})

    A hash of options.

Options Hash (options):

  • :realm (String)

    “API Authorization” The HTTP Basic realm.



121
122
123
124
# File 'lib/grape/api.rb', line 121

def http_basic(options = {}, &block)
  options[:realm] ||= "API Authorization"
  auth :http_basic, options, &block
end

.loggerObject



13
14
15
# File 'lib/grape/api.rb', line 13

def logger
  @logger ||= Logger.new($STDOUT)
end

.middlewareObject

Retrieve an array of the middleware classes and arguments that are currently applied to the application.



197
198
199
# File 'lib/grape/api.rb', line 197

def middleware
  settings_stack.inject([]){|a,s| a += s[:middleware] if s[:middleware]; a}
end

.namespace(space = nil, &block) ⇒ Object Also known as: group, resource, resources



163
164
165
166
167
168
169
170
171
# File 'lib/grape/api.rb', line 163

def namespace(space = nil, &block)
  if space || block_given?
    nest(block) do
      set(:namespace, space.to_s) if space
    end
  else
    Rack::Mount::Utils.normalize_path(settings_stack.map{|s| s[:namespace]}.join('/'))
  end
end

.post(*paths, &block) ⇒ Object



158
# File 'lib/grape/api.rb', line 158

def post(*paths, &block); route('POST', paths, &block) end

.prefix(prefix = nil) ⇒ Object

Define a root URL prefix for your entire API.



50
51
52
# File 'lib/grape/api.rb', line 50

def prefix(prefix = nil)
  prefix ? set(:root_prefix, prefix) : settings[:root_prefix]
end

.put(*paths, &block) ⇒ Object



159
# File 'lib/grape/api.rb', line 159

def put(*paths, &block); route('PUT', paths, &block) end

.reset!Object



17
18
19
20
21
# File 'lib/grape/api.rb', line 17

def reset!
  @settings = [{}]
  @route_set = Rack::Mount::RouteSet.new
  @prototype = nil
end

.route(methods, paths, &block) ⇒ Object

Defines a route that will be recognized by the Grape API.

Examples:

Defining a basic route.

class MyAPI < Grape::API
  route(:any, '/hello') do
    {:hello => 'world'}
  end
end

Parameters:

  • methods (HTTP Verb)

    One or more HTTP verbs that are accepted by this route. Set to ‘:any` if you want any verb to be accepted.

  • paths (String)

    One or more strings representing the URL segment(s) for this route.



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/grape/api.rb', line 138

def route(methods, paths, &block)
  methods = Array(methods)
  paths = ['/'] if paths == []
  paths = Array(paths)
  endpoint = build_endpoint(&block)
  options = {}
  options[:version] = /#{version.join('|')}/ if version
  
  methods.each do |method|
    paths.each do |path|
      path = Rack::Mount::Strexp.compile(compile_path(path), options, ['/'], true)
      route_set.add_route(endpoint, 
        :path_info => path, 
        :request_method => (method.to_s.upcase unless method == :any)
      )
    end
  end
end

.scope(name = nil, &block) ⇒ Object

Create a scope without affecting the URL.

Parameters:

  • name (Symbol) (defaults to: nil)

    Purely placebo, just allows to to name the scope to make the code more readable.



180
181
182
# File 'lib/grape/api.rb', line 180

def scope(name = nil, &block)
  nest(block)
end

.set(key, value) ⇒ Object

Set a configuration value for this namespace.

Parameters:

  • key (Symbol)

    The key of the configuration variable.

  • value (Object)

    The value to which to set the configuration variable.



44
45
46
# File 'lib/grape/api.rb', line 44

def set(key, value)
  @settings.last[key.to_sym] = value
end

.settingsObject

Settings are a stack, so when we want to access them they are merged in the order pushed.



31
32
33
# File 'lib/grape/api.rb', line 31

def settings
  @settings.inject({}){|f,h| f.merge!(h); f}
end

.settings_stackObject



35
36
37
# File 'lib/grape/api.rb', line 35

def settings_stack
  @settings
end

.use(middleware_class, *args) ⇒ Object

Apply a custom middleware to the API. Applies to the current namespace and any children, but not parents.

Parameters:

  • middleware_class (Class)

    The class of the middleware you’d like to inject.



189
190
191
192
# File 'lib/grape/api.rb', line 189

def use(middleware_class, *args)
  settings_stack.last[:middleware] ||= []
  settings_stack.last[:middleware] << [middleware_class, *args]        
end

.version(*new_versions, &block) ⇒ Object

Specify an API version.

Examples:

API with legacy support.

class MyAPI < Grape::API
  version 'v2'

  get '/main' do
    {:some => 'data'}
  end

  version 'v1' do
    get '/main' do
      {:legacy => 'data'}
    end
  end
end


71
72
73
# File 'lib/grape/api.rb', line 71

def version(*new_versions, &block)
  new_versions.any? ? nest(block){ set(:version, new_versions) } : settings[:version]
end