Grape(Ruby on Rails)

27
Building an API using GRAPE Presented By- Md. Main Uddin Rony

Transcript of Grape(Ruby on Rails)

Building an API using

GRAPE

Presented By-

Md. Main Uddin Rony

Outlines

What’s Grape?

Basic API

Add Prefix

Add Namespace

Add Module

Add version

Parameters

Declared

Using Helpers

Routes

Raise Exception

Exception Handling

API Format

Useful Resources

What’s Grape?

Generalized

Rapid

APIs

Erector

An opinionated

micro-framework

for creating RESTful

APIs in Ruby

•Powerful API framework

•Designed to run on Rack Application

•To fit into Sinatra and Rails Application

Installation

‘ gem install grape’

Or

gem 'grape‘ // using Bundler

Run bundle install.

Work with Rails

Place API files into and modify

Modify

Basic API

Add Prefix

Add Namespace

Add Namespace (Contd.)

Namespaces allow parameter definitions and apply to every method within the namespace.

Add Namespace(Contd.)

We can define a route parameter as namespace using

Add Module

If we want to mount on a path inside the mounted API itself:

Add Version

Add Version(Contd.)

Four Strategies:

❑ Path → →

❑ Header → →

❑ Param → →

❑ Accept-Version Header →

Parameters

Request parameters are available through the ”params” hash object.

Parameters are automatically populated from the request body on POST and PUT for form input, JSON and XML content-types.

Declared

Grape allows you to access only the parameters that have been declared by your ’params’ block. It filters out the params that have been passed, but are not

allowed.

Use Helpers

Routes

We can define requirements for your named route parameters using regular expressions on namespace or endpoint.

Raise Exception

We can abort the execution of an API method by raising errors with

We can also return JSON formatted objects by raising error! and passing a hash instead of a message.

Exception Handling

Grape can be told to rescue all exceptions and return them in the API format.

You can also rescue specific exceptions.

API Formats

If we do not specify any, Grape will support XML, JSON, BINARY, and TXT content-types. The default format is :txt

Advantages

1. Designed to run on rack or existing application frameworks such as Rails and Sinatra

2. It has built-in support for common conventions, including multiple formats, subdomain/prefix

restriction.

3. Versioning is very easy.

4. A lightweight framework which is loosely coupled with other application frameworks.

Useful Resources

1. https://github.com/intridea/grape

2. https://groups.google.com/forum/?fromgroups#!forum/ruby-grape

3. http://intridea.github.io/grape/docs/index.html

4. https://github.com/intridea/grape/wiki

5. http://confreaks.tv/videos/rubyconf2010-the-grapes-of-rapid

Questions??

THANK YOU!!!!