SlideShare a Scribd company logo
I can haz HTTP
Consuming and producing HTTP APIs in the
Ruby ecosystem
sidu ponnappa
kaiwren
@ponnappa
niranjan paranjape
achamian
@niranjan_p
Engineering

http://github.com/c42
Open Source
   (gem install) wrest
(gem install) pox_paginate
Not about HTTP libs
     not per se...
More about...
REST
caching
serialisation & deserialisation
authentication
stuff like that...
Producer / Consumer
Producer
I can haz HTTP - Consuming and producing HTTP APIs in the Ruby ecosystem
I can haz HTTP - Consuming and producing HTTP APIs in the Ruby ecosystem
digression
RESTful?
Leonard Richardson
L0: Plain Old Xml
L1: Resources



L0: Plain Old Xml
L2: HTTP Verbs



    L1: Resources



L0: Plain Old Xml
L3: Hypermedia



       L2: HTTP Verbs



    L1: Resources



L0: Plain Old Xml
reasonable compliance?
L2 is achievable with minimal
        effort in Rails
getting back to the point
Don’t mix machine stuff with
        human stuff
APIs are for machines
mixing the two causes trouble
I can haz HTTP - Consuming and producing HTTP APIs in the Ruby ecosystem
I can haz HTTP - Consuming and producing HTTP APIs in the Ruby ecosystem
I can haz HTTP - Consuming and producing HTTP APIs in the Ruby ecosystem
basically, doing this causes
           trouble
def index
  respond_to do |format|
                e




    format.html
    format.json { render :json => Project.all.to_json }
  end
end
because, people like usable
          apps
separate API controllers from
    website controllers
or beyond even that...
your app only exposes APIs

   your website is a separate application
that consumes these APIs; think NewTwitter
don’t design exclusively for
      ActiveResource
        it isn’t a standard
HTTP status codes
rails has nice defaults
  201 for creates
  401 for auth violations
  405 for L2 violations
  406 for Content-Type violations
  422 for invalid data
  500 for server faults
  200 for everything else
let rails help you
what they missed
404
409
assert on status codes
     gem install rspec-http

    response.should be_im_a_teapot
Authentication
OAuth 2 is nice
be an OAuth provider
  consistency makes life easier
https://
Caching
go beyond Rails’ local caches
the Cache-Control header is
        your friend
Versioning
successful APIs change
good versioning is critical
publish clear roadmaps and deprecate sensibly
Content Types
don’t tunnel
application/x-www-form-urlencoded
Accept headers
“http://localhost:3000/user.xml”
“http://localhost:3000/user.xml”
rails respects it
  you should use it
Important stuff that we’ve
       never done
Throttling
https://github.com/dambalah/api-throttling
             (thanks @godfoca)
Metering
Consumer
rails API vs. everything else
ActiveResource
60:40
the rest of the time you
     monkeypatch
 but that isn’t so easy, so be careful
ActiveResource works best
  inside a walled garden
          (IMHO)
Producer maturity
some APIs are weird
everyone’s standardizing on
           REST
     but it’s what they call REST
suffice to say, one size doesn’t
              fit all
 except for OAuth 2, which everyone’s adopting
building a clean domain model
       for the API is key
OAuth 2 is ridiculously easy to
      write a client for
                 #justSaying
 https://github.com/kaiwren/wrest/tree/master/
             examples/facebook_auth
authorisation on the other
hand still has no standard
     implementation
What should a good HTTP
   client do for you?
this one needs bullets
•   Verbs - should support GET, POST, PUT & DELETE.
•   If it supports PATCH & OPTIONS, epic.
•   Transparent deserialization of XML and JSON, with the option to easily add more
•   HTTP caching (RFC 2616)
•   Keep-alive connections (because negotiating SSL can get expensive)
•   Thread safety
•   Transparent compression/decompression using Accept-Encoding
•   A fluent, easy to use API
most importantly...
verbs
serialization
I rather like ActiveSupport
caching
 RFC 2616
thread safety
fluent api
is it easy to work with uris, because you’ll do a fair bit of
               that when building domains
is it easy to build a domain
       model using it?
logging/debugging
Shared stuff
serialization/deserialization
libxml
ActiveSupport::XmlMini.backend = 'Nokogiri'
Builder
Pure Ruby XML serializer. Pretty Fast.
     Just does String concats.
gotcha
no DOM for Builder
so no guarantee that you get valid XML
testing
this can be tricky
Conclusion
respect HTTP
respect REST constraints
spend less time messing with
         plumbing
focus on building a clean
     domain model
Photo credits
David Blackwell, Elephant in Room: http://www.flickr.com/photos/mobilestreetlife
Funny picture?




cat with mausambi hat
42


      Sidu Ponnappa               Niranjan Paranjape



http://twitter.com/ponnappa http://twitter.com/niranjan_p

https://github.com/kaiwren   https://github.com/achamian

More Related Content

PDF
Concurrent Ruby Application Servers
PDF
2021.laravelconf.tw.slides1
KEY
Concurrency in ruby
ODP
Servlet 3.1 Async I/O
PPT
Os Smarr
PPTX
Spring Boot Update
PPTX
Introduction to OWIN
ODP
Grape golilath
Concurrent Ruby Application Servers
2021.laravelconf.tw.slides1
Concurrency in ruby
Servlet 3.1 Async I/O
Os Smarr
Spring Boot Update
Introduction to OWIN
Grape golilath

What's hot (20)

PPT
Ruby vs Node ShiningRay Shanghai
PDF
Event Machine
PPT
OWIN (Open Web Interface for .NET)
PDF
C# ASP.NET WEB API APPLICATION DEVELOPMENT
PPTX
OWIN and Katana Project - Not Only IIS - NoIIS
PPTX
Owin and katana
PPT
Os Mcmahan
PPTX
Nom Nom: Consuming REST APIs
PPTX
Building a REST Service in minutes with Spring Boot
PDF
PHP Laravel Framework'üne Dalış
PDF
All the Laravel things: up and running to making $$
PPTX
How to extend (properly) and old Alfresco Share feature
PPTX
ASP.NET Core MVC + Web API with Overview
PPTX
Mini-Training Owin Katana
PPTX
Composer Lightning Talk
PPTX
Debugging the Web with Fiddler
PDF
A Day of REST
PDF
Symfony Live San Francisco 2017 - Symfony @ OpenSky
PDF
One does not simply "Upgrade to Rails 3"
PPTX
ASP.NET: Present and future
Ruby vs Node ShiningRay Shanghai
Event Machine
OWIN (Open Web Interface for .NET)
C# ASP.NET WEB API APPLICATION DEVELOPMENT
OWIN and Katana Project - Not Only IIS - NoIIS
Owin and katana
Os Mcmahan
Nom Nom: Consuming REST APIs
Building a REST Service in minutes with Spring Boot
PHP Laravel Framework'üne Dalış
All the Laravel things: up and running to making $$
How to extend (properly) and old Alfresco Share feature
ASP.NET Core MVC + Web API with Overview
Mini-Training Owin Katana
Composer Lightning Talk
Debugging the Web with Fiddler
A Day of REST
Symfony Live San Francisco 2017 - Symfony @ OpenSky
One does not simply "Upgrade to Rails 3"
ASP.NET: Present and future
Ad

Viewers also liked (20)

PPTX
Video Games and Reader's Advisory
PPTX
Transforming the Design Process
PDF
U L Budayakerja
PPT
World Tower Sculpture Proposal
KEY
Present Perfect: forms and uses
PPTX
Internetix 2009 Brian Final Version Jhb
PDF
Portent Webinar: Next-Level Segmentation
PPS
Luis Felipe Pacheco LLanes, Senior OCM
PDF
Java Script
PPT
Saved (part 2)
PPS
Orbul Si Ziaristul
PPT
Social Media & Small Business : Taking your first steps in Social Media
PPT
Trends In New Media Luncheon at Optsum 2010
PDF
SEO blogging best practices
PDF
2007 development of a who growth reference for school aged children and adole...
PPTX
This Transliterate Life
PPS
Rutina[1]
PDF
Experts On Credit Crisis
PDF
What IA, UX and SEO Can Learn from Each Other
PDF
The Universe Problem: Poll results, Facebook and the 2012 Presidential campaign
Video Games and Reader's Advisory
Transforming the Design Process
U L Budayakerja
World Tower Sculpture Proposal
Present Perfect: forms and uses
Internetix 2009 Brian Final Version Jhb
Portent Webinar: Next-Level Segmentation
Luis Felipe Pacheco LLanes, Senior OCM
Java Script
Saved (part 2)
Orbul Si Ziaristul
Social Media & Small Business : Taking your first steps in Social Media
Trends In New Media Luncheon at Optsum 2010
SEO blogging best practices
2007 development of a who growth reference for school aged children and adole...
This Transliterate Life
Rutina[1]
Experts On Credit Crisis
What IA, UX and SEO Can Learn from Each Other
The Universe Problem: Poll results, Facebook and the 2012 Presidential campaign
Ad

Similar to I can haz HTTP - Consuming and producing HTTP APIs in the Ruby ecosystem (20)

KEY
Rails services in the walled garden
PDF
Crafting APIs
PPS
Flickr Services
PPS
Flickr Services
PDF
Function as a Service
PPT
Web services - REST and SOAP
PPTX
Kiwipycon command line
PDF
REST in ( a mobile ) peace @ WHYMCA 05-21-2011
PPTX
Web Dev 21-01-2024.pptx
PPTX
Where is my scalable api?
PDF
What’s New in Rails 5.0?
PPTX
Where is my scalable API?
PDF
PHP is the King, nodejs is the Prince and Lua is the fool
PPT
Lamp
PPTX
API workshop: Introduction to APIs (TC Camp)
PDF
JHipster Conf 2018 : Connect your JHipster apps to the world of APIs with Ope...
PDF
Open API Architectural Choices Considerations
KEY
Matt Gauger - Lamp vs. the world - MKE PHP Users Group - December 14, 2010
PPTX
REST-API introduction for developers
PDF
Seattle StrongLoop Node.js Workshop
Rails services in the walled garden
Crafting APIs
Flickr Services
Flickr Services
Function as a Service
Web services - REST and SOAP
Kiwipycon command line
REST in ( a mobile ) peace @ WHYMCA 05-21-2011
Web Dev 21-01-2024.pptx
Where is my scalable api?
What’s New in Rails 5.0?
Where is my scalable API?
PHP is the King, nodejs is the Prince and Lua is the fool
Lamp
API workshop: Introduction to APIs (TC Camp)
JHipster Conf 2018 : Connect your JHipster apps to the world of APIs with Ope...
Open API Architectural Choices Considerations
Matt Gauger - Lamp vs. the world - MKE PHP Users Group - December 14, 2010
REST-API introduction for developers
Seattle StrongLoop Node.js Workshop

Recently uploaded (20)

PDF
Encapsulation theory and applications.pdf
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
Programs and apps: productivity, graphics, security and other tools
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Machine Learning_overview_presentation.pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Empathic Computing: Creating Shared Understanding
Encapsulation theory and applications.pdf
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
The Rise and Fall of 3GPP – Time for a Sabbatical?
Programs and apps: productivity, graphics, security and other tools
The AUB Centre for AI in Media Proposal.docx
Building Integrated photovoltaic BIPV_UPV.pdf
Machine Learning_overview_presentation.pptx
Encapsulation_ Review paper, used for researhc scholars
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Unlocking AI with Model Context Protocol (MCP)
20250228 LYD VKU AI Blended-Learning.pptx
Assigned Numbers - 2025 - Bluetooth® Document
Dropbox Q2 2025 Financial Results & Investor Presentation
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Network Security Unit 5.pdf for BCA BBA.
Chapter 3 Spatial Domain Image Processing.pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Empathic Computing: Creating Shared Understanding

I can haz HTTP - Consuming and producing HTTP APIs in the Ruby ecosystem

Editor's Notes

  • #2: \n
  • #3: \n
  • #4: \n
  • #5: \n
  • #6: \n
  • #7: \n
  • #8: \n
  • #9: \n
  • #10: Opensource we have done in this area\n
  • #11: This talk is not about NetHTTP vs libcurl\n
  • #12: \n
  • #13: \n
  • #14: \n
  • #15: \n
  • #16: \n
  • #17: \n
  • #18: This talk does have *some* structure; we’ll look at APIs from the perspective of the producer and the consumer. With a little bit left over for stuff that bridges the gap.\n
  • #19: \n
  • #20: Everyone talks about how easy it is to produce APIs with Sinatra and such like, but lets be honest. There’s an elephant in the room - those of you that freelance know exactly how many requests we get for APIs on Sinatra versus APIs on...\n
  • #21: [Handoff]\n\n...Rails. Love it or hate it, Rails has a standard way of producing APIs, and understanding what Rails can or cannot do for you is important. Sinatra does not have these constraints, so you’re free to roll APIs any way you want, so we’ll focus on the framework that does impose significant patterns.\n
  • #22: [achamian]\n\nBut before we launch into Rails’ capabilities, it’s important to put things into context first by talking a little about REST\n
  • #23: What is a RESTful API?\n
  • #24: For this we turn to Leonard Richardson who came up with a maturity model that has gotten so famous it has an acronym and looks like...\n
  • #25: ...this, popularly known as the Richardson Maturity Model, or RMM. \nIt begins with Level 0, which uses plain old xml (or a similar encoding format) to tunnel requests to a HTTP endpoint. Think RPC. Clearly Rails is better than this.\nNext comes Level 1, which introduces the concept of Resources - every URI represents a resource. Easy peasy. Rails makes it easy to do this - but you’re free to deviate.\nThen comes Level 2, which defines a certain set of constraints around how HTTP verbs are used. Rails violates the semantics by using PUT instead of PATCH - this was fixed on May 07 with Pull request #348, so future releases should be L2 compliant.\nFinally, we come to L3 which involves using hypermedia to define the edges of the state graph of an application using hypermedia links. This definitely isn’t in Rails. Yet.\n
  • #26: ...this, popularly known as the Richardson Maturity Model, or RMM. \nIt begins with Level 0, which uses plain old xml (or a similar encoding format) to tunnel requests to a HTTP endpoint. Think RPC. Clearly Rails is better than this.\nNext comes Level 1, which introduces the concept of Resources - every URI represents a resource. Easy peasy. Rails makes it easy to do this - but you’re free to deviate.\nThen comes Level 2, which defines a certain set of constraints around how HTTP verbs are used. Rails violates the semantics by using PUT instead of PATCH - this was fixed on May 07 with Pull request #348, so future releases should be L2 compliant.\nFinally, we come to L3 which involves using hypermedia to define the edges of the state graph of an application using hypermedia links. This definitely isn’t in Rails. Yet.\n
  • #27: ...this, popularly known as the Richardson Maturity Model, or RMM. \nIt begins with Level 0, which uses plain old xml (or a similar encoding format) to tunnel requests to a HTTP endpoint. Think RPC. Clearly Rails is better than this.\nNext comes Level 1, which introduces the concept of Resources - every URI represents a resource. Easy peasy. Rails makes it easy to do this - but you’re free to deviate.\nThen comes Level 2, which defines a certain set of constraints around how HTTP verbs are used. Rails violates the semantics by using PUT instead of PATCH - this was fixed on May 07 with Pull request #348, so future releases should be L2 compliant.\nFinally, we come to L3 which involves using hypermedia to define the edges of the state graph of an application using hypermedia links. This definitely isn’t in Rails. Yet.\n
  • #28: So what level of compliance can we achieve with a minimum of effort?\n
  • #29: [Handoff]\n\nI’d say an L2 is quite easily do-able in rails without too much effort. Now lets talk about how.\n
  • #30: [kaiwren]\n\nSo after that little digression, lets go back to what we were originally talking about - how to build APIs on Rails.\n
  • #31: [kaiwren]\n\nThis is one of the easiest thing to forget - APIs are for machines and software, websites are for people. Mixing the two is Not Good.\n
  • #32: \n
  • #33: \n
  • #34: Hollywood has shown us the consequence of mixing people stuff with machine stuff time and again, and it isn’t good.\n
  • #35: \n
  • #36: \n
  • #37: \n
  • #38: and REST cares only about state transitions. If you mix these, then remember that this only works in the most trivial of use cases. Beyond that...\n
  • #39: \n
  • #40: \n
  • #41: Your app doesn’t have a single HTML page. This is especially useful if you expect 3rd parties to use your APIs - you’re dogfooding your own stuff from day one.\n
  • #42: [Handoff]\n\nif your api is being consumed by 3rd parties, be aware that they will use a fairly eclectic collection of HTTP libs. What’s convenient/intuitive when using AR may be extremely obscure when using simple HTTP calls.\n
  • #43: [achamian]\n\nThe next thing everybody should keep an eye on when building Rails APIs are the HTTP status codes. There are many of them, and your APIs should respect them.\n
  • #44: The first thing everybody ignores when building Rails APIs are the HTTP status codes. There are many of them, and your APIs should respect them.\n
  • #45: Adhere to these defaults in the code you write. They’re there for a reason. Don’t, for example, return a 200 with an error message in the body - that’s bad form.\n
  • #46: There are, however, a couple of codes they deal with weirdly, or not at all\n
  • #47: The handling of 404s can be strange, driven as it is in certain cases by the ActiveRecord::RecordNotFound exception. Make sure that if a resource is not found, you’re always returning a 404 status code and you write a spec to expect it.\n
  • #48: Have a unique constraint on a resource identifier which is part of the input and not system assigned? When it’s violated, return a 409-Conflict and not a 422-Unprocessable entity.\n
  • #49: It’s important to lock these codes in because they mean a lot to the outside world. When building apis, make sure all your controller specs include assertions on the response code. I’ve got a simple gem that can help if you use rspec. Try it out. That asserts that a response has a code of 418.\n
  • #50: \n
  • #51: \n
  • #52: This way your application doesn’t need to deal with your own users through one auth mechanism and those that come through fb/twitter/github/sf through another\n
  • #53: Oauth 2 requires SSL, so do keep that in mind.\n
  • #54: \n
  • #55: \n
  • #56: If you have resources that don’t need to be refreshed as soon as they change, you should use an appropriate expires header to allow intermediate nodes on the network to cache them for a specified period of time. This can massively reduce load on your servers.\n
  • #57: \n
  • #58: \n
  • #59: Just like any library or gem, your users require visibility and stability. Whether you use URL based versioning (by including v1/v2/v3) in the API url, or by headers that specify the version, make sure your versioning roadmap is clear, consistent and sensible. Try maintaining backward compatibility as far as is reasonable.\n
  • #60: Content Types are rarely done wrong, so I won’t talk about them for too long. There’s only one thing that I’ve observed out here...\n
  • #61: ... is folks tunneling application/x-www-form-urlencoded over application/xml or application/json.\n
  • #62: \n
  • #63: \n
  • #64: a suffix of .xml or .json in the URI is to make it easier to look at api responses in the browser. While consuming an API you should stick to the Accept header.\n
  • #65: There are a couple of important things when dealing with APIs that I’ve never done and have no first-hand experience with\n
  • #66: Solved using rack middleware\n
  • #67: [Handoff]\n
  • #68: [kaiwren]\n
  • #69: Are you talking to a rails app (typically within your own walled garden) or to an API out on the internets?\n
  • #70: Let’s talk about the consumer that ships with Rails - ActiveResource\n
  • #71: ActiveResource follows the 60/40 rule not 80/20 - it works for the straightforward use cases, and does so smoothly and well\n
  • #72: Trying accessing the header information for a response\n
  • #73: \n
  • #74: \n
  • #75: Passing parameters for a post request. Accepting access token as a parameter to a Get over https \n
  • #76: \n
  • #77: \n
  • #78: \n
  • #79: You don’t need gems for OAuth2 clients. Just roll your own - it takes 20 minutes tops.\n
  • #80: \n
  • #81: \n
  • #82: \n
  • #83: \n
  • #84: \n
  • #85: \n
  • #86: \n
  • #87: \n
  • #88: \n
  • #89: \n
  • #90: Can I figure out the verb, the connection (if keep alive), corelate the req and response a situation where parallel threads are logging to the same log\n
  • #91: These are the bits that both producers and consumers deal with\n
  • #92: A significant proportion of the time an API takes to process something is spent doing serialisation and deserialization\n
  • #93: Remember to switch your deserialization backend from REXML to Nokogiri which uses the native libxml library. It’s way way faster.\n
  • #94: The default XML serializer in Rails is written in pure Ruby. It’s pretty fast, and there are drop in native alternatives based off libxml that are upto 50% faster, but that aren’t particularly popular.\n
  • #95: The big gotcha with builder occurs when you’re generating custom XML\n
  • #96: you want to run all the custom xml you create using builder’s DSLs through Nokogiri’s deserialise to make sure its valid XML in your specs\n
  • #97: In addition to controller specs, it makes sense to have full, live tests hitting a real server, especially if you’re integrating across multiple APIs that you’ve authored\n
  • #98: \n
  • #99: \n
  • #100: \n
  • #101: \n
  • #102: \n
  • #103: \n
  • #104: \n
  • #105: \n