SlideShare uma empresa Scribd logo
1 de 18
Simple REST Services with Sinatra
oisín hurley

ois.in@nis.io
@oisin
Those Pesky Servers

• Non-local


• Non-debuggable


• Non-restartable


• All remote and no control




                               I’ve been programming all day and
                              now I’ve no-one to restart the server.
                                          Botheration!
Do it yourself
Install Ruby

• You have Ruby already




• You have the Ruby Package Manager - gem
Install Sinatra




                    Sinatra is a DSL
             for creating Web applications
                      in Ruby with
                   MINIMAL EFFORT
Standard Example of Tinyness
Let’s Go Corkboard




                                                    Subject: xcaken
                                                    Date: 12 Jan 2011
                                                    Corkin hinder bar wearin achtung
                                                    keepin handercloppen keepin gestalt.
                                                    Lookinpeepers gewerkin waltz das
                                                    yodel auf keepin nine unter buerger.
                                                    Wunderbar er, ich heiden frau strudel
                                                    kaputt, uber wunderbar morgen,
                                                    sightseerin underbite, auf weiner ist.




https://github.com/oisin/corkboard_server_example
The RESTful bit
GET (read)
DELETE (delete)
PUT (create)
POST (update)




     ✂
Database




           Model




           http://datamapper.org/
JSON

                                  Unmarshall




Marshall
           model should provide own marshalling
JSON
Tests are cheap
Deployment

• Sinatra is Rack-compliant - Rack is a web server interface
Follow

• http://www.sinatrarb.com/documentation

• https://github.com/oisin/corkboard_server_example

Mais conteúdo relacionado

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Destaque

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
ThinkNow
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 

Destaque (20)

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 
ChatGPT webinar slides
ChatGPT webinar slidesChatGPT webinar slides
ChatGPT webinar slides
 

Simple REST Services With Sinatra

Notas do Editor

  1. Making web services for your mobile development\n
  2. Mobile developers have issues - primarily clients, but clients who have servers give that extra frisson of eyeroll, as one expects to have to deal with low-motivation IT staff in a different organization. A mobile developer would much rather have some control over a test server. If you want to make progress on your code at 3am, then you should be able to do so. Creative work is not a schedulable unit. As a pure mobile developer, maybe your server side skills are a little rusty. But you don’t want to commit to lots of learn time to re-learn a skill of which you only really really need a smidgen. This talk is for you.\n
  3. The solution, as always, is to replace the client’s IT department with a shell script. Or, better still, a Sinatra script. You can consider Sinatra to be Rails’ little brother - he hasn’t got to university yet and discovered beer and is still fairly trim. He doesn’t have the baggage of a lengthy relationship with ActionPack either and is able to focus on one thing. \n
  4. You have a Mac. Ergo you have Ruby and RubyGems installed already. RubyGems is the way you organize various Ruby libraries. It’s far from perfect, but makes life a lot easier for the kind of thing we are trying to deliver here.\n
  5. Once you have the RubyGems package manager installed, getting Sinatra is easy. Everything that Sinatra needs to run will be pulled in automagically.\n\nDSL is Domain-Specific Language - you knew that already, right?\n
  6. “Speed to Hello World” is no indication of the fitness of a particular approach or technology to a large or long-term task. But! We are doing small and short-term tasks, so that’s a WIN then. You can probably infer the rest of how the DSL works just from this teeny-tiny example, however let’s get into it and put together something marginally more complicated.\n
  7. The example I’m going to use is a ‘corkboard’. You have a corkboard (the server) and you can post notes to it (and remove them, and change them, and read them), and notes have a subject, the date they were posted and a piece of text, the note content proper. What is NOT going to be in this example is users, sessions and authentication. We might do them another time.\n
  8. The server is going to be RESTful, meaning I’m just going to provide a set of CRUD operations on a Resource. Each note is a Resource. You have all spotted at this point that these actions map directly to a subset of the standard HTTP verbs. That’s intentional. GET will return the details of a note, given the id in the database. PUT will insert a note in the database and then respond with the id of the new note. DELETE will remove the note from the database. POST will update the note in the database with some new content\n\nEnough! Next up is some Ruby code.\n
  9. Here we get a note with a particular id. \n1. The ‘:’ char indicates a ‘symbol’. Any symbols you put in that path up there get replaced into a dictionary called ‘params’ for use in the body the get. You can be smart about the patterns you use.\n2. ‘puts’ is just a print statement\n3. This loads a note from the database - we’re trying to match the :id to the primary key.\n4. Set the status to be a HTTP 404 code, not found!\n5. Yay, we’re good, set the status to be HTTP 200, ok.\n6. And set the body to be the JSON serialization of the note object.\nThe return just happens on exit.\n
  10. ① Deleting a note with the given id, when we receive the HTTP delete verb. This code does a get to see if the note is there in the database so it can give a better error status return. Another option would be to catch the database exception that happens when the delete fails because the key isn’t found. The ② destroy method removes the\nnote from the database.\n
  11. 1. Getting a little fancier now. This creates a note. We don’t need an id in the path, and we are reacting to the \nuse of the PUT verb.\n2. Here’s something new - we’re asking the JSON module to parse the content of the request we have just \nreceived into an object called ‘data’. This is a dynamic language, so the type of the ‘data’ is not established\nbefore execution time - in this case it’s going to be a dictionary, or hash.\n3. Checking for missing stuff - the note has to have a subject and content to be valid, otherwise we set a HTTP 400 status, Bad Request.\n4. Actually making the model object given the subject and content and adding some time recording.\n5. Saving the model object to the database.\n6. Returning the primary key of the object we’ve just added to the database so that the client can track it.\n
  12. A post updates the an identified note, maybe changing the subject or the content or both. It will also\nupdate the ‘updated_at’ field of the note. Nothing special to call out here, except perhaps the %w structure\nin the middle of the method. %w(subject content) just gives a collection of two strings “subject” and “content”,\nand the code iterates over these to update the target note with whatever has been part of the post body. The\nscissors is a cut error by me, sorry, there used to be a log message there that got snarfed. Next: DATABASE!\n
  13. Sinatra can use LOTS of different data sources. But that’s not something that concerns you. You do have \nsqlite3 on your mac AND you know how to muck about with it thanks to Core Data, so that’s the right thing\nto pick. We’re going to use DataMapper (another Ruby gem) to interface with it. \n1. Set up sqlite3 to point to a file in the current directory.\n2. Indicate your class is a model by just including DataMapper::Resource (easy!).\n3. You need to have a primary key in there, it will pick one called :id if it’s there, Serial means an increasing integer value!\n4. If you have :required => true, it means this field (column) can’t be null. There’s lots of modifiers like this, including defaults, key status. Check the DataMapper documentation for excruciating details.\n5. This finalize tells DataMapper that all of the models have been defined and now it’s time to nail things down.\n6. This tells DataMapper that if we make changes to the Note model and then run this again using a database that contains the *previous* Note model, then the DataMapper layer is to silently migrate the existing (old) database to put in the new information that has appeared in the changed model. This *won’t* remove stuff that has gone away from the model, so be aware of the potential of wasted columns. Not a problem for this work!\n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n