SlideShare une entreprise Scribd logo
1  sur  33
Ruby on Grape 
Andrii Furmanets
Ruby makes life easier
But REST-APIs are not easy
APIs in Rails are too entangled
Why can’t APIs have own 
framework?
GRAPE
Agenda 
• Installation 
• CRUD Actions 
• Namespace 
• Versioning 
• Parameter Validation 
• Basic Authentication 
• API Formats 
• Demo 
• Grape vs Rails 
• Resources
Installation 
Grape is a gem, to install it just install the 
gem: 
gem install grape 
If you're using Bundler, add the gem to 
Gemfile. 
gem 'grape‘
CRUD Actions (GET) 
class App < Grape::API 
get '/files', rabl: 'assets/collection' do 
@assets = Asset.all 
end 
end curl http://localhost:9292/files 
[{"asset":{"title":"My first zip 
file","id":1,"assetuploader":{}}},{"asset":{"title" 
:"My first zip file","id":2,"assetuploader":{}}}, 
… ]
CRUD Actions (GET) 
class App < Grape::API 
get '/files/:id', rabl: 'assets/item' do 
@asset = Asset[params[:id]] 
end 
end 
curl http://localhost:9292/files/1 
{"asset":{"title":"My first zip 
file","id":1,"url":"/public/uploads/ass 
ets/1/zip.zip","user":"N/A"}}
CRUD Actions (POST) 
class App < Grape::API 
post '/files', rabl: 'assets/item' do 
@asset = Asset.new params[:file] 
@asset.save 
end 
end 
curl -X POST -d 'file[title]=First file' 
http://localhost:9292/files 
{"asset":{"title":"First file","id":38, 
"url":null,"user":"N/A"}}
CRUD Actions (PUT) 
class App < Grape::API 
put '/files/:id', rabl: 'assets/item' do 
@asset = Asset[params[:id]] 
@asset.set(params[:file]).save 
end 
end 
curl -X PUT -d 'file[title]=Updated 
file' http://localhost:9292/files/40 
{"asset":{"title":"Updated 
file","id":40,"url":null,"user":"N/A"}}
CRUD Actions (DELETE) 
class App < Grape::API 
delete '/files/:id' do 
@asset = Asset[params[:id]] 
@asset.delete 
"File with id #{params[:id]} deleted" 
end 
end 
curl -X DELETE 
http://localhost:9292/files/39 
"File with id 39 deleted"
Namespace 
class App < Grape::API 
resource :files do 
get '/', rabl: 'assets/collection' do 
@assets = Asset.all 
end 
get '/:id', rabl: 'assets/item' do 
@asset = Asset[params[:id]] 
end 
post '/', rabl: 'assets/item' do 
@asset = Asset.new params[:file] 
@asset.save 
end 
… 
end 
end
Versioning 
• Path 
• Header 
• Accept-Version Header 
• Param
Versioning (Path) 
class App < Grape::API 
version 'v1', using: :path 
get '/files', rabl: 'assets/collection' do 
@assets = Asset.all 
end 
end 
curl http://localhost:9292/v1/files
Versioning (Header) 
class App < Grape::API 
version 'v1', using: :header, vendor: 'asset' 
get '/files', rabl: 'assets/collection' do 
@assets = Asset.all 
end 
end 
curl -H Accept=application/vnd.asset-v1+ 
json http://localhost:9292/files
Versioning (Accept-Version Header) 
class App < Grape::API 
version 'v1', using: :accept_version_header 
get '/files', rabl: 'assets/collection' do 
@assets = Asset.all 
end 
end 
curl -H "Accept-Version=v1" 
http://localhost:9292/files
Versioning (Param) 
class App < Grape::API 
version 'v1', using: :param 
get '/files', rabl: 'assets/collection' do 
@assets = Asset.all 
end 
end 
curl http://localhost:9292/files?apiver=v1
Versioning (Param) 
class App < Grape::API 
version 'v1', using: :param, parameter: "version" 
get '/files', rabl: 'assets/collection' do 
@assets = Asset.all 
end 
end 
curl http://localhost:9292/files?version=v1
Parameter Validation 
class App < Grape::API 
params do 
requires :id, type: Integer 
end 
get '/files/:id', rabl: 'assets/item' do 
@asset = Asset[params[:id]] 
end 
end 
curl http://localhost:9292/files/1 
{"asset":{"title":"My first zip file","id":1, 
"url":"/public/uploads/assets/1/zip.zip“ 
,"user":"N/A"}} 
curl http://localhost:9292/files/wrong 
{"error":"id is invalid"}
Parameter Validation 
class App < Grape::API 
params do 
requires :id, type: Integer 
optional :text, type: String, 
regexp: /^[a-z]+$/ 
end 
get '/files/:id', rabl: 'assets/item' do 
@asset = Asset[params[:id]] 
end 
end 
curl http://localhost:9292/files/1 
{"asset":{"title":"My first zip file"}} 
curl http://localhost:9292/files/1?text=example 
{"asset":{"title":"My first zip file",}} 
curl http://localhost:9292/files/1?text=Example 
{"error":"text is invalid"}
Basic Authentication 
class App < Grape::API 
http_basic do |handler, password| 
@@user = User.where(handler: handler).first 
@@user.authorize? password 
end 
get '/files/:id', rabl: 'assets/item' do 
@asset = Asse[params[:id]] 
end 
end
API Formats 
class App < Grape::API 
format :json 
get '/files', rabl: 'assets/item' do 
@asset = Asse.all 
end 
end
API Formats 
class App < Grape::API 
format :json 
default_format :json 
get '/files', rabl: 'assets/item' do 
@asset = Asse.all 
end 
end
Grape vs Rails
Grape vs Rails 
ab (apache-bench) is a tool 
for benchmarking your 
Hypertext Transfer Protocol 
(HTTP) server
Ruby Version Grape Rails::API 
Ruby 1.9.3-p448 Time taken for tests: 
40.799 seconds 
Time taken for tests: 
89.975 seconds 
Requests per second: 
2451.07 
Requests per second: 
1111.42 
Time per request: 
0.408 
Time per request: 
0.900 
Grape vs Rails
Ruby Version Grape Rails::API 
Ruby 2.0.0-p247 Time taken for tests: 
44.902 seconds 
Time taken for tests: 
107.761 seconds 
Requests per second: 
2227.10 
Requests per second: 
927.98 
Time per request: 
0.449 
Time per request: 
1.078 
Grape vs Rails
Ruby Version Grape Rails::API 
JRuby 1.7.4 Time taken for tests: 
12.664 seconds 
Time taken for tests: 
33.278 seconds 
Requests per second: 
7896.50 
Requests per second: 
3005.01 
Time per request: 
0.507 
Time per request: 
1.331 
Grape vs Rails
Resources 
Google Group - Get Grape help here. 
API Documentation - YARD documentation for the 
Grape API. 
The Grapes of Rapid - RubyConf 2010 presentation 
about Grape. Slides 
Grape Wiki - A collection of more resources and 
gems.
Questions?

Contenu connexe

Tendances

Euroclojure2014: Schema & Swagger - making your Clojure web APIs more awesome
Euroclojure2014: Schema & Swagger - making your Clojure web APIs more awesomeEuroclojure2014: Schema & Swagger - making your Clojure web APIs more awesome
Euroclojure2014: Schema & Swagger - making your Clojure web APIs more awesomeMetosin Oy
 
Laravel Forge: Hello World to Hello Production
Laravel Forge: Hello World to Hello ProductionLaravel Forge: Hello World to Hello Production
Laravel Forge: Hello World to Hello ProductionJoe Ferguson
 
Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1Vikas Chauhan
 
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory CourseRuby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Coursepeter_marklund
 
Don't worry be API with Slim framework and Joomla
Don't worry be API with Slim framework and JoomlaDon't worry be API with Slim framework and Joomla
Don't worry be API with Slim framework and JoomlaPierre-André Vullioud
 
Windows Containers - Microsoft Ignite The Tour
Windows Containers - Microsoft Ignite The TourWindows Containers - Microsoft Ignite The Tour
Windows Containers - Microsoft Ignite The TourEran Stiller
 
Asp.Net Core MVC , Razor page , Entity Framework Core
Asp.Net Core MVC , Razor page , Entity Framework CoreAsp.Net Core MVC , Razor page , Entity Framework Core
Asp.Net Core MVC , Razor page , Entity Framework Coremohamed elshafey
 
Consuming REST services with ActiveResource
Consuming REST services with ActiveResourceConsuming REST services with ActiveResource
Consuming REST services with ActiveResourceWolfram Arnold
 
The Evolution of Airbnb's Frontend
The Evolution of Airbnb's FrontendThe Evolution of Airbnb's Frontend
The Evolution of Airbnb's FrontendSpike Brehm
 
10 Laravel packages everyone should know
10 Laravel packages everyone should know10 Laravel packages everyone should know
10 Laravel packages everyone should knowPovilas Korop
 
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & MobileIVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & MobileAmazon Web Services Japan
 
Put a Button on It: Removing Barriers to Going Fast
Put a Button on It: Removing Barriers to Going FastPut a Button on It: Removing Barriers to Going Fast
Put a Button on It: Removing Barriers to Going FastOSCON Byrum
 
Real World Fun with ActiveResource
Real World Fun with ActiveResourceReal World Fun with ActiveResource
Real World Fun with ActiveResourceRob C
 
Ruby w/o Rails (Олександр Сімонов)
Ruby w/o Rails (Олександр Сімонов)Ruby w/o Rails (Олександр Сімонов)
Ruby w/o Rails (Олександр Сімонов)Fwdays
 
Building an API in Node with HapiJS
Building an API in Node with HapiJSBuilding an API in Node with HapiJS
Building an API in Node with HapiJSLoc Nguyen
 
O que há de novo no Rails 3
O que há de novo no Rails 3O que há de novo no Rails 3
O que há de novo no Rails 3Hugo Baraúna
 
MidwestPHP 2016 - Adventures in Laravel 5
MidwestPHP 2016 - Adventures in Laravel 5 MidwestPHP 2016 - Adventures in Laravel 5
MidwestPHP 2016 - Adventures in Laravel 5 Joe Ferguson
 

Tendances (20)

Euroclojure2014: Schema & Swagger - making your Clojure web APIs more awesome
Euroclojure2014: Schema & Swagger - making your Clojure web APIs more awesomeEuroclojure2014: Schema & Swagger - making your Clojure web APIs more awesome
Euroclojure2014: Schema & Swagger - making your Clojure web APIs more awesome
 
Laravel Forge: Hello World to Hello Production
Laravel Forge: Hello World to Hello ProductionLaravel Forge: Hello World to Hello Production
Laravel Forge: Hello World to Hello Production
 
Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1
 
Intro to Laravel
Intro to LaravelIntro to Laravel
Intro to Laravel
 
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory CourseRuby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
 
Don't worry be API with Slim framework and Joomla
Don't worry be API with Slim framework and JoomlaDon't worry be API with Slim framework and Joomla
Don't worry be API with Slim framework and Joomla
 
Windows Containers - Microsoft Ignite The Tour
Windows Containers - Microsoft Ignite The TourWindows Containers - Microsoft Ignite The Tour
Windows Containers - Microsoft Ignite The Tour
 
Asp.Net Core MVC , Razor page , Entity Framework Core
Asp.Net Core MVC , Razor page , Entity Framework CoreAsp.Net Core MVC , Razor page , Entity Framework Core
Asp.Net Core MVC , Razor page , Entity Framework Core
 
Consuming REST services with ActiveResource
Consuming REST services with ActiveResourceConsuming REST services with ActiveResource
Consuming REST services with ActiveResource
 
The Evolution of Airbnb's Frontend
The Evolution of Airbnb's FrontendThe Evolution of Airbnb's Frontend
The Evolution of Airbnb's Frontend
 
10 Laravel packages everyone should know
10 Laravel packages everyone should know10 Laravel packages everyone should know
10 Laravel packages everyone should know
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & MobileIVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile
 
Cocoa on-rails-3rd
Cocoa on-rails-3rdCocoa on-rails-3rd
Cocoa on-rails-3rd
 
Put a Button on It: Removing Barriers to Going Fast
Put a Button on It: Removing Barriers to Going FastPut a Button on It: Removing Barriers to Going Fast
Put a Button on It: Removing Barriers to Going Fast
 
Real World Fun with ActiveResource
Real World Fun with ActiveResourceReal World Fun with ActiveResource
Real World Fun with ActiveResource
 
Ruby w/o Rails (Олександр Сімонов)
Ruby w/o Rails (Олександр Сімонов)Ruby w/o Rails (Олександр Сімонов)
Ruby w/o Rails (Олександр Сімонов)
 
Building an API in Node with HapiJS
Building an API in Node with HapiJSBuilding an API in Node with HapiJS
Building an API in Node with HapiJS
 
O que há de novo no Rails 3
O que há de novo no Rails 3O que há de novo no Rails 3
O que há de novo no Rails 3
 
MidwestPHP 2016 - Adventures in Laravel 5
MidwestPHP 2016 - Adventures in Laravel 5 MidwestPHP 2016 - Adventures in Laravel 5
MidwestPHP 2016 - Adventures in Laravel 5
 

En vedette

AHS-592 October 2015 Facebook V1
AHS-592 October 2015 Facebook V1AHS-592 October 2015 Facebook V1
AHS-592 October 2015 Facebook V1Erica Beimesche
 
история Demo 2011
история Demo 2011история Demo 2011
история Demo 2011vova123367
 
Crea y cuida tu reputación online (Araba Encounter 2014)
Crea y cuida tu reputación online (Araba Encounter 2014)Crea y cuida tu reputación online (Araba Encounter 2014)
Crea y cuida tu reputación online (Araba Encounter 2014)Jesús Lizarraga
 
Fickler, Tammy Ce114 Unit 9 Final
Fickler, Tammy Ce114 Unit 9 FinalFickler, Tammy Ce114 Unit 9 Final
Fickler, Tammy Ce114 Unit 9 FinalTammy Fickler
 
Nubes de palabras sonia
Nubes de palabras soniaNubes de palabras sonia
Nubes de palabras soniaSonia Mora
 
Muntatu webgune osoa 4 ordutan Worpressekin
Muntatu webgune osoa 4 ordutan WorpressekinMuntatu webgune osoa 4 ordutan Worpressekin
Muntatu webgune osoa 4 ordutan WorpressekinDani Reguera Bakhache
 
Simple Web Services With Sinatra and Heroku
Simple Web Services With Sinatra and HerokuSimple Web Services With Sinatra and Heroku
Simple Web Services With Sinatra and HerokuOisin Hurley
 
PwC eFörvaltningsdagarna 2010 11 18
PwC eFörvaltningsdagarna 2010 11 18PwC eFörvaltningsdagarna 2010 11 18
PwC eFörvaltningsdagarna 2010 11 18Carl-Johan Wahlberg
 
Irish currency - St Vincent Paul school
Irish currency - St Vincent Paul schoolIrish currency - St Vincent Paul school
Irish currency - St Vincent Paul schoolnumeracyenglish
 
Digital Humanities: A brief introduction to the field
Digital Humanities: A brief introduction to the fieldDigital Humanities: A brief introduction to the field
Digital Humanities: A brief introduction to the fieldaelang
 

En vedette (18)

Exposicion fermin toro maestria
Exposicion fermin toro maestriaExposicion fermin toro maestria
Exposicion fermin toro maestria
 
AHS-592 October 2015 Facebook V1
AHS-592 October 2015 Facebook V1AHS-592 October 2015 Facebook V1
AHS-592 October 2015 Facebook V1
 
I know who iam upload
I know who iam uploadI know who iam upload
I know who iam upload
 
история Demo 2011
история Demo 2011история Demo 2011
история Demo 2011
 
Docente Ante Las TICS
Docente Ante Las TICSDocente Ante Las TICS
Docente Ante Las TICS
 
Crea y cuida tu reputación online (Araba Encounter 2014)
Crea y cuida tu reputación online (Araba Encounter 2014)Crea y cuida tu reputación online (Araba Encounter 2014)
Crea y cuida tu reputación online (Araba Encounter 2014)
 
Fickler, Tammy Ce114 Unit 9 Final
Fickler, Tammy Ce114 Unit 9 FinalFickler, Tammy Ce114 Unit 9 Final
Fickler, Tammy Ce114 Unit 9 Final
 
New text document
New text documentNew text document
New text document
 
Nubes de palabras sonia
Nubes de palabras soniaNubes de palabras sonia
Nubes de palabras sonia
 
Transcomplejidad contemporánea
Transcomplejidad contemporáneaTranscomplejidad contemporánea
Transcomplejidad contemporánea
 
Muntatu webgune osoa 4 ordutan Worpressekin
Muntatu webgune osoa 4 ordutan WorpressekinMuntatu webgune osoa 4 ordutan Worpressekin
Muntatu webgune osoa 4 ordutan Worpressekin
 
Web Scraping
Web ScrapingWeb Scraping
Web Scraping
 
Simple Web Services With Sinatra and Heroku
Simple Web Services With Sinatra and HerokuSimple Web Services With Sinatra and Heroku
Simple Web Services With Sinatra and Heroku
 
Construcción disciplinaria del saber
Construcción disciplinaria del saberConstrucción disciplinaria del saber
Construcción disciplinaria del saber
 
PwC eFörvaltningsdagarna 2010 11 18
PwC eFörvaltningsdagarna 2010 11 18PwC eFörvaltningsdagarna 2010 11 18
PwC eFörvaltningsdagarna 2010 11 18
 
Bill of exchange
Bill of exchangeBill of exchange
Bill of exchange
 
Irish currency - St Vincent Paul school
Irish currency - St Vincent Paul schoolIrish currency - St Vincent Paul school
Irish currency - St Vincent Paul school
 
Digital Humanities: A brief introduction to the field
Digital Humanities: A brief introduction to the fieldDigital Humanities: A brief introduction to the field
Digital Humanities: A brief introduction to the field
 

Similaire à Ruby On Grape

2011 a grape odyssey
2011   a grape odyssey2011   a grape odyssey
2011 a grape odysseyMike Hagedorn
 
Using and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareUsing and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareAlona Mekhovova
 
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜崇之 清水
 
Building Serverless Applications with AWS Chalice
Building Serverless Applications with AWS ChaliceBuilding Serverless Applications with AWS Chalice
Building Serverless Applications with AWS ChaliceAmazon Web Services
 
Rapid Prototyping FTW!!!
Rapid Prototyping FTW!!!Rapid Prototyping FTW!!!
Rapid Prototyping FTW!!!cloudbring
 
Making a small QA system with Docker
Making a small QA system with DockerMaking a small QA system with Docker
Making a small QA system with DockerNaoki AINOYA
 
REST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in CodeigniterREST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in CodeigniterSachin G Kulkarni
 
Automate your automation with Rudder’s API! \o/
Automate your automation with Rudder’s API! \o/Automate your automation with Rudder’s API! \o/
Automate your automation with Rudder’s API! \o/RUDDER
 
From System Engineer to Gopher
From System Engineer to GopherFrom System Engineer to Gopher
From System Engineer to GopherI-Fan Wang
 
Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs
 Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs
Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbsAWS Chicago
 
Building Better Web APIs with Rails
Building Better Web APIs with RailsBuilding Better Web APIs with Rails
Building Better Web APIs with RailsAll Things Open
 
Using Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in RubyUsing Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in RubyLaunchAny
 
Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkDaniel Spector
 
Rails Engine | Modular application
Rails Engine | Modular applicationRails Engine | Modular application
Rails Engine | Modular applicationmirrec
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Racksickill
 
Alfresco Development Framework Basic
Alfresco Development Framework BasicAlfresco Development Framework Basic
Alfresco Development Framework BasicMario Romano
 

Similaire à Ruby On Grape (20)

Intro to Rack
Intro to RackIntro to Rack
Intro to Rack
 
Rack
RackRack
Rack
 
RoR guide_p1
RoR guide_p1RoR guide_p1
RoR guide_p1
 
2011 a grape odyssey
2011   a grape odyssey2011   a grape odyssey
2011 a grape odyssey
 
Rack
RackRack
Rack
 
Using and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareUsing and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middleware
 
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
RESTful API を Chalice で紐解く 〜 Python Serverless Microframework for AWS 〜
 
Building Serverless Applications with AWS Chalice
Building Serverless Applications with AWS ChaliceBuilding Serverless Applications with AWS Chalice
Building Serverless Applications with AWS Chalice
 
Rapid Prototyping FTW!!!
Rapid Prototyping FTW!!!Rapid Prototyping FTW!!!
Rapid Prototyping FTW!!!
 
Making a small QA system with Docker
Making a small QA system with DockerMaking a small QA system with Docker
Making a small QA system with Docker
 
REST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in CodeigniterREST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in Codeigniter
 
Automate your automation with Rudder’s API! \o/
Automate your automation with Rudder’s API! \o/Automate your automation with Rudder’s API! \o/
Automate your automation with Rudder’s API! \o/
 
From System Engineer to Gopher
From System Engineer to GopherFrom System Engineer to Gopher
From System Engineer to Gopher
 
Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs
 Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs
Serverless Framework Workshop - Tyler Hendrickson, Chicago/burbs
 
Building Better Web APIs with Rails
Building Better Web APIs with RailsBuilding Better Web APIs with Rails
Building Better Web APIs with Rails
 
Using Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in RubyUsing Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in Ruby
 
Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end Framework
 
Rails Engine | Modular application
Rails Engine | Modular applicationRails Engine | Modular application
Rails Engine | Modular application
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Rack
 
Alfresco Development Framework Basic
Alfresco Development Framework BasicAlfresco Development Framework Basic
Alfresco Development Framework Basic
 

Dernier

A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 

Dernier (20)

A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 

Ruby On Grape

  • 1. Ruby on Grape Andrii Furmanets
  • 3. But REST-APIs are not easy
  • 4. APIs in Rails are too entangled
  • 5. Why can’t APIs have own framework?
  • 7. Agenda • Installation • CRUD Actions • Namespace • Versioning • Parameter Validation • Basic Authentication • API Formats • Demo • Grape vs Rails • Resources
  • 8. Installation Grape is a gem, to install it just install the gem: gem install grape If you're using Bundler, add the gem to Gemfile. gem 'grape‘
  • 9. CRUD Actions (GET) class App < Grape::API get '/files', rabl: 'assets/collection' do @assets = Asset.all end end curl http://localhost:9292/files [{"asset":{"title":"My first zip file","id":1,"assetuploader":{}}},{"asset":{"title" :"My first zip file","id":2,"assetuploader":{}}}, … ]
  • 10. CRUD Actions (GET) class App < Grape::API get '/files/:id', rabl: 'assets/item' do @asset = Asset[params[:id]] end end curl http://localhost:9292/files/1 {"asset":{"title":"My first zip file","id":1,"url":"/public/uploads/ass ets/1/zip.zip","user":"N/A"}}
  • 11. CRUD Actions (POST) class App < Grape::API post '/files', rabl: 'assets/item' do @asset = Asset.new params[:file] @asset.save end end curl -X POST -d 'file[title]=First file' http://localhost:9292/files {"asset":{"title":"First file","id":38, "url":null,"user":"N/A"}}
  • 12. CRUD Actions (PUT) class App < Grape::API put '/files/:id', rabl: 'assets/item' do @asset = Asset[params[:id]] @asset.set(params[:file]).save end end curl -X PUT -d 'file[title]=Updated file' http://localhost:9292/files/40 {"asset":{"title":"Updated file","id":40,"url":null,"user":"N/A"}}
  • 13. CRUD Actions (DELETE) class App < Grape::API delete '/files/:id' do @asset = Asset[params[:id]] @asset.delete "File with id #{params[:id]} deleted" end end curl -X DELETE http://localhost:9292/files/39 "File with id 39 deleted"
  • 14. Namespace class App < Grape::API resource :files do get '/', rabl: 'assets/collection' do @assets = Asset.all end get '/:id', rabl: 'assets/item' do @asset = Asset[params[:id]] end post '/', rabl: 'assets/item' do @asset = Asset.new params[:file] @asset.save end … end end
  • 15. Versioning • Path • Header • Accept-Version Header • Param
  • 16. Versioning (Path) class App < Grape::API version 'v1', using: :path get '/files', rabl: 'assets/collection' do @assets = Asset.all end end curl http://localhost:9292/v1/files
  • 17. Versioning (Header) class App < Grape::API version 'v1', using: :header, vendor: 'asset' get '/files', rabl: 'assets/collection' do @assets = Asset.all end end curl -H Accept=application/vnd.asset-v1+ json http://localhost:9292/files
  • 18. Versioning (Accept-Version Header) class App < Grape::API version 'v1', using: :accept_version_header get '/files', rabl: 'assets/collection' do @assets = Asset.all end end curl -H "Accept-Version=v1" http://localhost:9292/files
  • 19. Versioning (Param) class App < Grape::API version 'v1', using: :param get '/files', rabl: 'assets/collection' do @assets = Asset.all end end curl http://localhost:9292/files?apiver=v1
  • 20. Versioning (Param) class App < Grape::API version 'v1', using: :param, parameter: "version" get '/files', rabl: 'assets/collection' do @assets = Asset.all end end curl http://localhost:9292/files?version=v1
  • 21. Parameter Validation class App < Grape::API params do requires :id, type: Integer end get '/files/:id', rabl: 'assets/item' do @asset = Asset[params[:id]] end end curl http://localhost:9292/files/1 {"asset":{"title":"My first zip file","id":1, "url":"/public/uploads/assets/1/zip.zip“ ,"user":"N/A"}} curl http://localhost:9292/files/wrong {"error":"id is invalid"}
  • 22. Parameter Validation class App < Grape::API params do requires :id, type: Integer optional :text, type: String, regexp: /^[a-z]+$/ end get '/files/:id', rabl: 'assets/item' do @asset = Asset[params[:id]] end end curl http://localhost:9292/files/1 {"asset":{"title":"My first zip file"}} curl http://localhost:9292/files/1?text=example {"asset":{"title":"My first zip file",}} curl http://localhost:9292/files/1?text=Example {"error":"text is invalid"}
  • 23. Basic Authentication class App < Grape::API http_basic do |handler, password| @@user = User.where(handler: handler).first @@user.authorize? password end get '/files/:id', rabl: 'assets/item' do @asset = Asse[params[:id]] end end
  • 24. API Formats class App < Grape::API format :json get '/files', rabl: 'assets/item' do @asset = Asse.all end end
  • 25. API Formats class App < Grape::API format :json default_format :json get '/files', rabl: 'assets/item' do @asset = Asse.all end end
  • 26.
  • 28. Grape vs Rails ab (apache-bench) is a tool for benchmarking your Hypertext Transfer Protocol (HTTP) server
  • 29. Ruby Version Grape Rails::API Ruby 1.9.3-p448 Time taken for tests: 40.799 seconds Time taken for tests: 89.975 seconds Requests per second: 2451.07 Requests per second: 1111.42 Time per request: 0.408 Time per request: 0.900 Grape vs Rails
  • 30. Ruby Version Grape Rails::API Ruby 2.0.0-p247 Time taken for tests: 44.902 seconds Time taken for tests: 107.761 seconds Requests per second: 2227.10 Requests per second: 927.98 Time per request: 0.449 Time per request: 1.078 Grape vs Rails
  • 31. Ruby Version Grape Rails::API JRuby 1.7.4 Time taken for tests: 12.664 seconds Time taken for tests: 33.278 seconds Requests per second: 7896.50 Requests per second: 3005.01 Time per request: 0.507 Time per request: 1.331 Grape vs Rails
  • 32. Resources Google Group - Get Grape help here. API Documentation - YARD documentation for the Grape API. The Grapes of Rapid - RubyConf 2010 presentation about Grape. Slides Grape Wiki - A collection of more resources and gems.