Build Great APIS with Grape

grape

 

ruby 1.9.3 + rails 3.2.18

add to the Gemfile

```ruby
# API
gem 'grape', '0.7.0'
gem 'grape-entity', '0.4.4'
```

bundle install

to load the api, edit file config/application.rb

```ruby
    config.paths.add "app/api", :glob => "**/*.rb"
    config.autoload_paths += %W(#{config.root}/app/api)
```

make a file app/api/api.rb

then the base api path is http://localhost:3000/api/v1/
we use mount to manage our api, this makes the structure is clear
just to make a folder and puts your code there


```ruby
class API < Grape::API
  prefix 'api'
  version 'v1', using: :path
  mount Account::API
end
```

so where is the Account::API is defined?
create a file app/api/account/api.rb

```ruby
module Account
  class API < Grape::API
      resource :users do
          desc "Return a status."
        params do
            requires :id, type: Integer, desc: "user id."
        end
        route_param :id do
            get do
              User.find(params[:id])
            end
        end
    end

    get "all_users" do
      User.all
    end
  end
end

```
add this to the routes.rb

```ruby
mount API => '/'
```

test the api

```ruby
curl http://localhost:3000/api/v1/users/1.json
```

{"age":29,"created_at":"2014-12-02T08:15:37Z","id":1,"name":"zhangsan","updated_at":"2014-12-02T08:15:37Z"}%

```ruby
curl http://localhost:3000/api/v1/all_users.json
```

[{"age":29,"created_at":"2014-12-02T08:15:37Z","id":1,"name":"zhangsan","updated_at":"2014-12-02T08:15:37Z"},{"age":29,"created_at":"2014-12-02T09:08:15Z","id":2,"name":"zhang2","updated_at":"2014-12-02T09:08:15Z"}]%


https://github.com/intridea/grape
http://icodeit.org/2013/08/quick-api-development-by-grape/
http://www.350351.com/bianchengyuyan/Ruby_on_Rails/410344.html

wellcome to read my weixin:  ruby程序员

 

你可能感兴趣的:(api,REST,grape)