Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
G

grape

> 编程语言
Open source

An opinionated framework for creating REST-like APIs in Ruby.

10.0K stars0 likes5 views
WebsiteGitHub

About

An opinionated framework for creating REST-like APIs in Ruby.

What is Grape?

Grape is a REST-like API framework for Ruby. It's designed to run on Rack or complement existing web application frameworks such as Rails and Sinatra by providing a simple DSL to easily develop RESTful APIs. It has built-in support for common conventions, including multiple formats, subdomain/prefix restriction, content negotiation, versioning and much more.

Stable Release

You're reading the documentation for the stable release of Grape, which should be 4.1.0. The current stable release is 4.0.1.

Project Resources

  • Grape Website
  • Documentation
  • Need help? Open an Issue
  • Follow us on Twitter

Grape for Enterprise

Available as part of the Tidelift Subscription.

The maintainers of Grape are working with Tidelift to deliver commercial support and maintenance. Save time, reduce risk, and improve code health, while paying the maintainers of Grape. Click here for more details.

Installation

Ruby 3.3 or newer is required.

Grape is available as a gem, to install it run:

bundle add grape

Basic Usage

Grape APIs are Rack applications that are created by subclassing Grape::API. Below is a simple example showing some of the more common features of Grape in the context of recreating parts of the Twitter API.

…

Rails 7.1

Grape's deprecator will be added to your application's deprecators automatically as :grape, so that your application's configuration can be applied to it.

Mounting

All

By default Grape will compile the routes on the first route, but it is possible to pre-load routes using the compile! method.

ruby
Twitter::API.compile!

This can be added to your config.ru (if using rackup), application.rb (if using rails), or any file that loads your server.

Rack

The above sample creates a Rack application that can be run from a rackup config.ru file with rackup:

ruby
run Twitter::API

(With pre-loading you can use)

ruby
Twitter::API.compile!
run Twitter::API

And would respond to the following routes:

GET /api/statuses/public_timeline
GET /api/statuses/home_timeline
GET /api/statuses/:id
POST /api/statuses
PUT /api/statuses/:id
DELETE /api/statuses/:id

Grape will also automatically respond to HEAD and OPTIONS for all GET, and just OPTIONS for all other routes.

Alongside Sinatra (or other frameworks)

If you wish to mount Grape alongside another Rack framework such as Sinatra, you can do so easily using Rack::Cascade:

ruby
# Example config.ru

require 'sinatra'
require 'grape'

class API < Grape::API
  get :hello do
    { hello: 'world' }
  end
end

class Web < Sinatra::Base
  get '/' do
    'Hello world.'
  end
end

use Rack::Session::Cookie
run Rack::Cascade.new [Web, API]

Note that order of loading apps using Rack::Cascade matters. The grape application must be last if you want to raise custom 404 errors from grape (such as error!('Not Found',404)). If the grape application is not last and returns 404 or 405 response, cascade utilizes that as a signal to try the next app. This may lead to undesirable behavior showing the wrong 404 page from the wrong app.

Rails

Place API files into app/api. Rails expects a subdirectory that matches the name of the Ruby module and a file name that matches the name of the class. In our example, the file name location and directory for Twitter::API should be app/api/twitter/api.rb.

Modify config/routes:

ruby
mount Twitter::API => '/'

Zeitwerk

Rails's default autoloader is Zeitwerk. By default, it inflects api as Api instead of API. To make our example work, you need to uncomment the lines at the bottom of config/initializers/inflections.rb, and add API as an acronym:

ruby
ActiveSupport::Inflector.inflections(:en) do |inflect|
  inflect.acronym 'API'
end

Modules

You can mount multiple API implementations inside another one. These don't have to be different versions, but may be components of the same API.

ruby
class Twitter::API < Grape::API
  mount Twitter::APIv1
  mount Twitter::APIv2
end

You can also mount on a path, which is similar to using prefix inside the mounted API itself.

ruby
class Twitter::API < Grape::API
  mount Twitter::APIv1 => '/v1'
end

Declarations as before/after/rescue_from can be placed before or after mount. In any case they will be inherited.

ruby
class Twitter::API < Grape::API
  before do
    header 'X-Base-Header', 'will be defined for all APIs that are mounted below'
  end

  rescue_from :all do
    error!({ "error" => "Internal Server Error" }, 500)
  end

  mount Twitter::Users
  mount Twitter::Search

  after do
    clean_cache!
  end

  rescue_from ZeroDivisionError do
    error!({ "error" => "Not found" }, 404)
  end
end

Remounting

You can mount the same endpoints in two different locations.

ruby
class Voting::API < Grape::API
  namespace 'votes' do
    get do
      # Your logic
    end

    post do
      # Your logic
    end
  end
end

class Post::API < Grape::API
  mount Voting::API
end

class Comment::API < Grape::API
  mount Voting::API
end

Assuming that the post and comment endpoints are mounted in /posts and /comments, you should now be able to do get /posts/votes, post /posts/votes, get /comments/votes and post /comments/votes.

Mount Configuration

You can configure remountable endpoints to change how they behave according to where they are mounted.

ruby
class Voting::API < Grape::API
  namespace 'votes' do
    desc "Vote for your #{configuration[:votable]}"
    get do
      # Your logic
    end
  end
end

class Post::API < Grape::API
  mount Voting::API, with: { votable: 'posts' }
end

class Comment::API < Grape::API
  mount Voting::API, with: { votable: 'comments' }
end

Note that if you're passing a hash as the first parameter to mount, you will need to explicitly put () around parameters:

ruby
# good
mount({ ::Some::Api => '/some/api' }, with: { condition: true })

# bad
mount ::Some::Api => '/some/api', with: { condition: true }

You can access configuration on the class (to use as dynamic attributes), inside blocks (like namespace)

If you want logic happening based on a configuration, you can use the helper given.

ruby
class ConditionalEndpoint::API < Grape::API
  given configuration[:some_setting] do
    get 'mount_this_endpoint_conditionally' do
      configuration[:configurable_response]
    end
  end
end

If you want a block of logic running every time an endpoint is mounted (within which you can access the configuration Hash)

ruby
class ConditionalEndpoint::API < Grape::API
  mounted do
    YourLogger.info "This API was mounted at: #{Time.now}"

    get configuration[:endpoint_name] do
      configuration[:configurable_response]
    end
  end
end

More complex results can be achieved by using mounted as an expression within which the configuration is already evaluated as a Hash.

ruby
class ExpressionEndpointAPI < Grape::API
  get(mounted { configuration[:route_name] || 'default_name' }) do
    # some logic
  end
end
…

Versioning

You have the option to provide various versions of your API by establishing a separate Grape::API class for each offered version and then integrating them into a primary Grape::API class. Ensure that newer versions are mounted before older ones. The default approach to versioning directs the request to the subsequent Rack middleware if a specific version is not found.

ruby
require 'v1'
require 'v2'
require 'v3'
class App < Grape::API
  mount V3
  mount V2
  mount V1
end

To maintain the same endpoints from earlier API versions without rewriting them, you can indicate multiple versions within the previous API versions.

ruby
class V1 < Grape::API
  version 'v1', 'v2', 'v3'

  get '/foo' do
    # your code for GET /foo
  end

  get '/other' do
    # your code for GET /other
  end
end

class V2 < Grape::API
  version 'v2', 'v3'

  get '/var' do
    # your code for GET /var
  end
end

class V3 < Grape::API
  version 'v3'

  get '/foo' do
    # your new code for GET /foo
  end
end

Using the example provided, the subsequent endpoints will be accessible across various versions:

bash
GET /v1/foo
GET /v1/other
GET /v2/foo # => Same behavior as v1
GET /v2/other # => Same behavior as v1
GET /v2/var # => New endpoint not available in v1
GET /v3/foo # => Different behavior to v1 and v2
GET /v3/other # => Same behavior as v1 and v2
GET /v3/var # => Same behavior as v2

There are four strategies in which clients can reach your API's endpoints: :path, :header, :accept_version_header and :param. The default strategy is :path.

Strategies

Path

ruby
version 'v1', using: :path

Using this versioning strategy, clients should pass the desired version in the URL.

bash
curl http://localhost:9292/v1/statuses/public_timeline

Header

ruby
version 'v1', using: :header, vendor: 'twitter'

Currently, Grape only supports versioned media types in the following format:

vnd.vendor-and-or-resource-v1234+format

Basically all tokens between the final - and the + will be interpreted as the version.

Using this versioning strategy, clients should pass the desired version in the HTTP Accept header.

bash
curl -H Accept:application/vnd.twitter-v1+json http://localhost:9292/statuses/public_timeline

By default, the first matching version is used when no Accept header is supplied. This behavior is similar to routing in Rails. To circumvent this default behavior, one could use the :strict option. When this option is set to true, a 406 Not Acceptable error is returned when no correct Accept header is supplied.

When an invalid Accept header is supplied, a 406 Not Acceptable error is returned if the :cascade option is set to false. Otherwise a 404 Not Found error is returned by Rack if no other route matches.

Grape will evaluate the relative quality preference included in Accept headers and default to a quality of 1.0 when omitted. In the following example a Grape API that supports XML and JSON in that order will return JSON:

bash
curl -H "Accept: text/xml;q=0.8, application/json;q=0.9" localhost:1234/resource

Accept-Version Header

ruby
version 'v1', using: :accept_version_header

Using this versioning strategy, clients should pass the desired version in the HTTP Accept-Version header.

bash
curl -H "Accept-Version:v1" http://localhost:9292/statuses/public_timeline

By default, the first matching version is used when no Accept-Version header is supplied. This behavior is similar to routing in Rails. To circumvent this default behavior, one could use the :strict option. When this option is set to true, a 406 Not Acceptable error is returned when no correct Accept-Version header is supplied and the :cascade option is set to false. Otherwise a 404 Not Found error is returned by Rack if no other route matches.

Param

ruby
version 'v1', using: :param

Using this versioning strategy, clients should pass the desired version as a request parameter, either in the URL query string or in the request body.

bash
curl http://localhost:9292/statuses/public_timeline?apiver=v1

The default name for the query parameter is 'apiver' but can be specified using the :parameter option.

ruby
version 'v1', using: :param, pa

Issues· 241 open

View all issuesOpen on GitHub
  • #3003

    Let a `rescue_from` handler propagate an exception instead of rendering it

    Updated Sep 24, 2026
  • #2979

    No public replacement for custom inheritable namespace settings in Grape 4.0?

    Updated Sep 22, 2026
  • #2487

    Include Rack::TempFileReaper in Grape ?

    feature requestyou can helpUpdated Jul 8, 2026
  • #1382

    Modify the VENDOR_VERSION_HEADER_REGEX to support/recognize matches on the HAL (hal+json) format

    bug?Updated Apr 25, 2026
  • #1491

    GraphQL to the RESTque

    discuss!Updated Nov 6, 2025
  • #2446

    Introduce standard gem ?

    discuss!choreUpdated Aug 27, 2025
  • #2562

    Grape for Enterprise on README redirects to a sales pitch

    choreUpdated May 8, 2025
  • #2522

    A mechanism to configure global before hooks

    feature requestUpdated Jan 16, 2025
  • #2238

    Rails 7 has removed ActiveSupport::Dependencies. How should reloading be done now?

    bug?you can helpUpdated Oct 11, 2024
  • #2415

    Recognize_path should account for HTTP method

    feature requestUpdated Oct 8, 2024

> Tags

Rubyapigrapehacktoberfestruby

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 29, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言