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

Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsAndrey Dotsenko
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 

Dernier (20)

Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 

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.