SlideShare une entreprise Scribd logo
1  sur  54
PARTY +
REST =
WIN!
BUILDING A RESTFUL WEB
SERVICE AS A COMPANION APP
FOR A LIVE EVENT
Jimmy Sieben
Lead Programmer, Gearbox Software
Twitter: @jimmys
jimmy.sieben@gearboxsoftware.com
A WORD ABOUT ME
I have been programming for 20+ years (15 professionally)
I am a game maker since 1995
I joined Gearbox in 2002
Network & Game Programming on multiple titles
• Halo: Combat Evolved (PC)
• Brothers in Arms: Road to Hill 30 (PC/Xbox)
• Brothers in Arms: Hell’s Highway (PC/PS3/Xbox 360)
• Borderlands 1 (PC/PS3/Xbox 360)
• Borderlands 2 (PC/PS3/Xbox 360)
WHAT ARE
WEB
SERVICES?
WHAT ARE WEB
SERVICES?
Web services enable devices to communicate over the web
HTTP is used as the underlying protocol
Data is sent and received in a machine-readable encoding
• XML
• JSON
• Protocol Buffers
• Various vendor-specific encodings
Services are written in a wide variety of languages
Many frameworks exist to support creating Web Services
WHY WEB SERVICES?
Provide API for a Web Application
HTTP is a well-known protocol
HTTP easily traverses firewalls
Take advantage of widely deployed tools
Every language implements it well
Stateless design is simple to implement and scale
WHAT ARE WEB
SERVICES USED FOR?
Social Networking
Software as a Service
Infrastructure as a Service
System Integration
Mashups
WEB SERVICE
ARCHITECTURES
Two dominant architectures for Web Services exist:
SOAP / XML-RPC
• Focused on exposing business rules and state
• Formal descriptions of protocol, automated tools
• Relies on complex infrastructure components
• XML is usually the encoding
RESTful
• Focused on resources and relationships between them
• Informal specs; not a standard – a technique or style
• Typically simpler and lighter weight
• JSON is a popular encoding
WHAT ARE
RESTFUL
SERVICES?
REPRESENTATIONAL
STATE
TRANSFER
Architecture described by Roy Fielding in his Doctoral
dissertation Architectural Styles and the Design of Network-
based Software Architectures (2000) available here:
http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm
• Client–server
• Stateless
• Cacheable
• Layered system
• Uniform interface
• Code on demand (optional)
PRINCIPLES OF
RESTFUL SERVICES
• Identification of Resources
• Identify resources via URIs
• Resources are independent of representation
• Manipulate Resources Through Representations
• Resource representation & associated metadata is enough
information for a client to modify or delete it
• Self-descriptive Messages
• MIME types determine how to interpret content
• Cache control defined by the response
• HATEOAS: Hypermedia As The Engine of Application State
• Clients make state transitions based on actions defined in
representations
OH, CRUD!
Use HTTP Verbs on Resources
Create
Read
Update
Delete
POST
GET
PUT
DELETE
MIME TYPES
DESCRIBE CONTENT
• RFC 2046 describes a system to identify content format
• Syntax: type/subtype; optional parameters
• image/jpeg
• text/html; charset=UTF-8
• HTTP Headers use these to negotiate content
• Accept allows client to request format
• Content-type required on responses to identify format
• Common MIME types
• text/plain
• text/html
• application/json
• application/xml
• image/jpeg
• image/png
HTTP STATUS CODES
• RESTful Services use these to communicate application state
• 1xx: Informational
• 2xx: Successful
• 200 Success
• 201 Created
• 3xx: Redirection
• 301 Moved Permanently
• 4xx: Client Error
• 401 Unauthorized
• 404 Not Found
• 5xx: Server Error
• 500 Internal Server Error
• 503 Service Unavailable
Source: https://cwiki.apache.org/WINK/1-introduction-to-apache-wink.html
RESTFUL SERVICE
Person: {name: “Bob”, age: 25}
http://www.example.com/person/123
{name: “Bob”, age: 25, mother:
“http://www.example.com/person/78}
{name: “Martha”, age: 58, mother:
“http://www.example.com/person/11”}
Define the Resources
important for your
application
Expose resources as
paths in the URI
Build relationships
between those
resources
DESIGNING A
RESTFUL SERVICE
CREATE: POST TO A
COLLECTION
REQUEST
POST /people HTTP/1.1
Content-type:
application/json
Content-length: nnn
{name: “Bob”, age: 25}
RESPONSE
HTTP/1.1 201 Created
Content-type:
application/json
Content-length: nnn
Location:
http://www.example.com/person/123
Etag: 74bef98a330ac
{name: “Bob”, age: 25,
updated: “2013-01-
31T18:24:36Z”}
READ: GET A
RESOURCE
REQUEST
GET /person/123 HTTP/1.1
Accept: application/json
RESPONSE
HTTP/1.1 200 OK
Content-type:
application/json
Content-length: nnn
Location:
http://www.example.com/person/123
Etag: 74bef98a330ac
{name: “Bob”, age: 25,
updated: “2013-01-
31T18:24:36Z”}
UPDATE: PUT A
RESOURCE
REQUEST
PUT /person/123 HTTP/1.1
Content-type:
application/json
Content-length: nnn
{name: “Bob”, age: 24}
RESPONSE
HTTP/1.1 200 OK
Content-type:
application/json
Content-length: nnn
Location:
http://www.example.com/person/123
Etag: 83c092fdb32b
{name: “Bob”, age: 24,
updated: “2013-01-
31T18:47:02Z”}
DELETE: DELETE A
RESOURCE
REQUEST
DELETE /person/123 HTTP/1.1
DELETE /person/123 HTTP/1.1
Authorization: Basic
X738bjNhsk2j==
RESPONSE
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Basic
realm=“administration”
HTTP/1.1 204 No Content
BE CAREFUL WITH BASIC
AUTHORIZATION
• Basic Authorization passes credentials Base64 encoded
• This is easily decoded – equivalent to cleartext!
• Fine for toy examples, be careful for production services
• Can be OK to use if the service is deployed on SSL
• Recommended to consider application-level scheme such
as OAuth 2.0
• See the following for more information
• http://blog.apigee.com/detail/api_authentication_and_how_
it_got_that_way_from_http_basic_to_oauth_2.0
• http://stackoverflow.com/questions/549/the-definitive-
guide-to-forms-based-website-authentication
PARTY ON!
A RESTFUL SERVICE IN PRACTICE
GEARBOX HOLIDAY
PARTY
For the past few years, the party features an extended
presentation that the partygoers watch as gifts are awarded
For 2012, we wanted to extend this with some interactivity
The idea was born to allow participants to vote on their
smartphones by building a companion app
• Ugly Christmas Sweater Contest
• White Elephant – Choose Their Fate
The companion app tabulates votes via RESTful service
The presentation asks the service for the results in real-time
ARCHITECTURE
Party Web Service
(Ruby/Rails)
Presentation
(Flash/ActionScript)
Companion App
(HTML5/JS)
Admin UI
(Ruby/Rails)
Splash screen while voting is closed
COMPANION APP
The ballot is not yet open for voting
PRESENTATION
Voting is happening on the Companion App
PRESENTATION
Participants can tap on sweaters any number of times to vote
COMPANION APP
Polls closed, winner chosen
PRESENTATION
White Elephant voting is in progress
PRESENTATION
Participants can tap on words any number of times to vote
COMPANION APP
BACKEND
SERVICE ADMINISTRATION
Ballots defined, CRUD operations, controls to manually activate & deactivate
SERVICE ADMINISTRATION
http://partyservice/ballots
Choices defined, CRUD operations
SERVICE ADMINISTRATION
http://partyservice/ballot/1/choices
Edit a choice, view the choice
SERVICE ADMINISTRATION
http://partyservice/ballot/1/choice/2
Entrants defined, CRUD operations
SERVICE ADMINISTRATION
http://partyservice/entrants
Edit an entrant, view an entrant
SERVICE ADMINISTRATION
http://partyservice/entrant/3
IMPLEMENT
THE
SERVICE &
APP
IMPLEMENTING
A RESOURCE
Examples are in Ruby 1.9 with Rails 3.2
The principles apply to any RESTful design, irrespective of
language and framework
First we will look at the routes which define resources
Then we will see CRUD operations implemented along with a
special custom action
Finally we will bring it all together in the companion app and
the presentation
Defines Resources and provides a means to access them via HTTP verbs
ROUTES: THE HEART OF THE SERVICE
This method supports JSON encoding and creates a ballot from the POST body
CREATE BALLOT
This method displays a ballot either in HTML for the admin UI, or JSON for the app
READ BALLOT
This method reads the JSON ballot, saves it, then renders again in desired format
UPDATE BALLOT
This method deletes a ballot. In the admin UI, it redirects to the ballot listing
DELETE BALLOT
Not 100% RESTful, but a convenient pattern to add another verb
CUSTOM METHOD: ACTIVATE
Also not 100% RESTful, this method records a vote
CUSTOM METHOD: RECORD VOTE
JavaScript in the browser loads choices from the service, inspecting JSON result
APP: LOAD CHOICES
JavaScript in the browser sends votes to a custom action
APP: VOTE ON A CHOICE
Presentation ActionScript prefetches the ballot, choices, and images (HTTP GET)
PRESENTATION: PREFETCH
Presentation ActionScript activates a ballot to open the polls (HTTP POST)
PRESENTATION: ACTIVATE BALLOT
Presentation ActionScript requests results in real-time (HTTP GET)
PRESENTATION: GET RESULTS
HOW DID IT
DO?
RESULTS!
The party service, app, and presentation were a big hit
We processed over 50,000 votes in approximately 10 minutes
Partygoers reported they really enjoyed the experience
Future work:
• More interactivity
• Mini-game?
PARTING THOUGHTS
RESTful Web Services are great because they are a simple
way to take advantage of the whole web pipeline
There are some downsides
• Ad-hoc implementations mean little guidance, especially
on crucial topics like security and I18N
• There’s not necessarily one way to do things
• May need to roll-your-own connections to services from
different vendors
Embrace the architecture, be pragmatic
Build a companion app that pushes the boundary
Have fun!
ADDITIONAL
RESOURCES
Sun Cloud API exploration
http://kenai.com/projects/suncloudapis/pages/HelloCloud
REST Anti-Patterns
http://www.infoq.com/articles/rest-anti-patterns
RESTFul Web Services
Leonard Richardson, Sam Ruby
O'Reilly Media, May 2007
Jimmy Sieben
Lead Programmer, Gearbox Software
Twitter: @jimmys
jimmy.sieben@gearboxsoftware.com

Contenu connexe

En vedette

The institutional landscape of Japanese Politics
The institutional landscape of Japanese PoliticsThe institutional landscape of Japanese Politics
The institutional landscape of Japanese Politics
Arzumetova Dilroba
 
Go #5 political process 2011 2012
Go #5 political process 2011 2012Go #5 political process 2011 2012
Go #5 political process 2011 2012
mrgault
 
Accessories catalogue ru_preview
Accessories catalogue ru_previewAccessories catalogue ru_preview
Accessories catalogue ru_preview
PocketBook Int
 
Guhsd digital natives
Guhsd digital nativesGuhsd digital natives
Guhsd digital natives
kmesquita
 
PocketBook accessories catalogue 2011
PocketBook accessories catalogue 2011PocketBook accessories catalogue 2011
PocketBook accessories catalogue 2011
PocketBook Int
 
Game tech sm
Game tech smGame tech sm
Game tech sm
iLiv_stu
 

En vedette (20)

The institutional landscape of Japanese Politics
The institutional landscape of Japanese PoliticsThe institutional landscape of Japanese Politics
The institutional landscape of Japanese Politics
 
Muncy unit 5 cdp utilize media and material
Muncy unit 5 cdp utilize media and materialMuncy unit 5 cdp utilize media and material
Muncy unit 5 cdp utilize media and material
 
Go #5 political process 2011 2012
Go #5 political process 2011 2012Go #5 political process 2011 2012
Go #5 political process 2011 2012
 
Miguel ángel asturias
Miguel ángel asturiasMiguel ángel asturias
Miguel ángel asturias
 
Accessories catalogue ru_preview
Accessories catalogue ru_previewAccessories catalogue ru_preview
Accessories catalogue ru_preview
 
New grad groups 2011 112
New grad groups 2011 112New grad groups 2011 112
New grad groups 2011 112
 
Ch 25 11 21
Ch 25 11 21Ch 25 11 21
Ch 25 11 21
 
Intro to mis
Intro to misIntro to mis
Intro to mis
 
o
oo
o
 
Guhsd digital natives
Guhsd digital nativesGuhsd digital natives
Guhsd digital natives
 
Vinifikacija
VinifikacijaVinifikacija
Vinifikacija
 
PocketBook accessories catalogue 2011
PocketBook accessories catalogue 2011PocketBook accessories catalogue 2011
PocketBook accessories catalogue 2011
 
Webinar baot induction 2011
Webinar baot induction 2011Webinar baot induction 2011
Webinar baot induction 2011
 
Di2011
Di2011Di2011
Di2011
 
Game tech sm
Game tech smGame tech sm
Game tech sm
 
Best Friend, Happy Birthday Rosa Yisell Gomez
Best Friend, Happy Birthday Rosa Yisell GomezBest Friend, Happy Birthday Rosa Yisell Gomez
Best Friend, Happy Birthday Rosa Yisell Gomez
 
Gastro
GastroGastro
Gastro
 
Victor Cimperman's Portfolio
Victor Cimperman's PortfolioVictor Cimperman's Portfolio
Victor Cimperman's Portfolio
 
DesignThinking. Discovery the future
DesignThinking. Discovery the futureDesignThinking. Discovery the future
DesignThinking. Discovery the future
 
นำเสนอ..ศก.พอเพียง
นำเสนอ..ศก.พอเพียงนำเสนอ..ศก.พอเพียง
นำเสนอ..ศก.พอเพียง
 

Similaire à Party + REST = Win

Top 10 Lessons Learned from the Netflix API - OSCON 2014
Top 10 Lessons Learned from the Netflix API - OSCON 2014Top 10 Lessons Learned from the Netflix API - OSCON 2014
Top 10 Lessons Learned from the Netflix API - OSCON 2014
Daniel Jacobson
 

Similaire à Party + REST = Win (20)

Kaltura Inspire Webinar: API Driven Video Platform - The Key to Scalability a...
Kaltura Inspire Webinar: API Driven Video Platform - The Key to Scalability a...Kaltura Inspire Webinar: API Driven Video Platform - The Key to Scalability a...
Kaltura Inspire Webinar: API Driven Video Platform - The Key to Scalability a...
 
Vidfy Video platform
Vidfy Video platformVidfy Video platform
Vidfy Video platform
 
Создание API, которое полюбят разработчики. Глубокое погружение
Создание API, которое полюбят разработчики. Глубокое погружениеСоздание API, которое полюбят разработчики. Глубокое погружение
Создание API, которое полюбят разработчики. Глубокое погружение
 
Building the Eventbrite API Ecosystem
Building the Eventbrite API EcosystemBuilding the Eventbrite API Ecosystem
Building the Eventbrite API Ecosystem
 
#SPSottawa The SharePoint Framework and The Microsoft Graph on steroids with ...
#SPSottawa The SharePoint Framework and The Microsoft Graph on steroids with ...#SPSottawa The SharePoint Framework and The Microsoft Graph on steroids with ...
#SPSottawa The SharePoint Framework and The Microsoft Graph on steroids with ...
 
#SPSNYC 2018 Migrate your custom components to the #SharePoint Framework #SPFX
#SPSNYC 2018 Migrate your custom components to the #SharePoint Framework #SPFX#SPSNYC 2018 Migrate your custom components to the #SharePoint Framework #SPFX
#SPSNYC 2018 Migrate your custom components to the #SharePoint Framework #SPFX
 
Top 10 Lessons Learned from the Netflix API - OSCON 2014
Top 10 Lessons Learned from the Netflix API - OSCON 2014Top 10 Lessons Learned from the Netflix API - OSCON 2014
Top 10 Lessons Learned from the Netflix API - OSCON 2014
 
Oscon2014 Netflix API - Top 10 Lessons Learned
Oscon2014 Netflix API - Top 10 Lessons LearnedOscon2014 Netflix API - Top 10 Lessons Learned
Oscon2014 Netflix API - Top 10 Lessons Learned
 
Apps 101 - Moving to the SharePoint 2013 App Model - Presented 7/27/13 at Sha...
Apps 101 - Moving to the SharePoint 2013 App Model - Presented 7/27/13 at Sha...Apps 101 - Moving to the SharePoint 2013 App Model - Presented 7/27/13 at Sha...
Apps 101 - Moving to the SharePoint 2013 App Model - Presented 7/27/13 at Sha...
 
Embracing HTTP in the era of API’s
Embracing HTTP in the era of API’sEmbracing HTTP in the era of API’s
Embracing HTTP in the era of API’s
 
[WSO2 Integration Summit Nairobi 2019] Role of Integration in an API Driven W...
[WSO2 Integration Summit Nairobi 2019] Role of Integration in an API Driven W...[WSO2 Integration Summit Nairobi 2019] Role of Integration in an API Driven W...
[WSO2 Integration Summit Nairobi 2019] Role of Integration in an API Driven W...
 
Introduction to the Windows Live Platform
Introduction to the Windows Live PlatformIntroduction to the Windows Live Platform
Introduction to the Windows Live Platform
 
The Who, What, Why and How of Active Directory Federation Services (AD FS)
The Who, What, Why and How of Active Directory Federation Services (AD FS)The Who, What, Why and How of Active Directory Federation Services (AD FS)
The Who, What, Why and How of Active Directory Federation Services (AD FS)
 
Portal and Intranets
Portal and Intranets Portal and Intranets
Portal and Intranets
 
Developer’s Independence Day: Introducing the SharePoint App Model
Developer’s Independence Day:Introducing the SharePoint App ModelDeveloper’s Independence Day:Introducing the SharePoint App Model
Developer’s Independence Day: Introducing the SharePoint App Model
 
API & Backend Integration
API & Backend IntegrationAPI & Backend Integration
API & Backend Integration
 
#SPSToronto The SharePoint Framework and the Microsoft Graph on steroids with...
#SPSToronto The SharePoint Framework and the Microsoft Graph on steroids with...#SPSToronto The SharePoint Framework and the Microsoft Graph on steroids with...
#SPSToronto The SharePoint Framework and the Microsoft Graph on steroids with...
 
Maintaining the Front Door to Netflix
Maintaining the Front Door to NetflixMaintaining the Front Door to Netflix
Maintaining the Front Door to Netflix
 
Lessons learned on the Azure API Stewardship Journey.pptx
Lessons learned on the Azure API Stewardship Journey.pptxLessons learned on the Azure API Stewardship Journey.pptx
Lessons learned on the Azure API Stewardship Journey.pptx
 
Architecture app
Architecture appArchitecture app
Architecture app
 

Dernier

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 

Dernier (20)

Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 

Party + REST = Win

  • 1. PARTY + REST = WIN! BUILDING A RESTFUL WEB SERVICE AS A COMPANION APP FOR A LIVE EVENT Jimmy Sieben Lead Programmer, Gearbox Software Twitter: @jimmys jimmy.sieben@gearboxsoftware.com
  • 2. A WORD ABOUT ME I have been programming for 20+ years (15 professionally) I am a game maker since 1995 I joined Gearbox in 2002 Network & Game Programming on multiple titles • Halo: Combat Evolved (PC) • Brothers in Arms: Road to Hill 30 (PC/Xbox) • Brothers in Arms: Hell’s Highway (PC/PS3/Xbox 360) • Borderlands 1 (PC/PS3/Xbox 360) • Borderlands 2 (PC/PS3/Xbox 360)
  • 4. WHAT ARE WEB SERVICES? Web services enable devices to communicate over the web HTTP is used as the underlying protocol Data is sent and received in a machine-readable encoding • XML • JSON • Protocol Buffers • Various vendor-specific encodings Services are written in a wide variety of languages Many frameworks exist to support creating Web Services
  • 5. WHY WEB SERVICES? Provide API for a Web Application HTTP is a well-known protocol HTTP easily traverses firewalls Take advantage of widely deployed tools Every language implements it well Stateless design is simple to implement and scale
  • 6. WHAT ARE WEB SERVICES USED FOR? Social Networking Software as a Service Infrastructure as a Service System Integration Mashups
  • 7. WEB SERVICE ARCHITECTURES Two dominant architectures for Web Services exist: SOAP / XML-RPC • Focused on exposing business rules and state • Formal descriptions of protocol, automated tools • Relies on complex infrastructure components • XML is usually the encoding RESTful • Focused on resources and relationships between them • Informal specs; not a standard – a technique or style • Typically simpler and lighter weight • JSON is a popular encoding
  • 9. REPRESENTATIONAL STATE TRANSFER Architecture described by Roy Fielding in his Doctoral dissertation Architectural Styles and the Design of Network- based Software Architectures (2000) available here: http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm • Client–server • Stateless • Cacheable • Layered system • Uniform interface • Code on demand (optional)
  • 10. PRINCIPLES OF RESTFUL SERVICES • Identification of Resources • Identify resources via URIs • Resources are independent of representation • Manipulate Resources Through Representations • Resource representation & associated metadata is enough information for a client to modify or delete it • Self-descriptive Messages • MIME types determine how to interpret content • Cache control defined by the response • HATEOAS: Hypermedia As The Engine of Application State • Clients make state transitions based on actions defined in representations
  • 11. OH, CRUD! Use HTTP Verbs on Resources Create Read Update Delete POST GET PUT DELETE
  • 12. MIME TYPES DESCRIBE CONTENT • RFC 2046 describes a system to identify content format • Syntax: type/subtype; optional parameters • image/jpeg • text/html; charset=UTF-8 • HTTP Headers use these to negotiate content • Accept allows client to request format • Content-type required on responses to identify format • Common MIME types • text/plain • text/html • application/json • application/xml • image/jpeg • image/png
  • 13. HTTP STATUS CODES • RESTful Services use these to communicate application state • 1xx: Informational • 2xx: Successful • 200 Success • 201 Created • 3xx: Redirection • 301 Moved Permanently • 4xx: Client Error • 401 Unauthorized • 404 Not Found • 5xx: Server Error • 500 Internal Server Error • 503 Service Unavailable
  • 15. Person: {name: “Bob”, age: 25} http://www.example.com/person/123 {name: “Bob”, age: 25, mother: “http://www.example.com/person/78} {name: “Martha”, age: 58, mother: “http://www.example.com/person/11”} Define the Resources important for your application Expose resources as paths in the URI Build relationships between those resources DESIGNING A RESTFUL SERVICE
  • 16. CREATE: POST TO A COLLECTION REQUEST POST /people HTTP/1.1 Content-type: application/json Content-length: nnn {name: “Bob”, age: 25} RESPONSE HTTP/1.1 201 Created Content-type: application/json Content-length: nnn Location: http://www.example.com/person/123 Etag: 74bef98a330ac {name: “Bob”, age: 25, updated: “2013-01- 31T18:24:36Z”}
  • 17. READ: GET A RESOURCE REQUEST GET /person/123 HTTP/1.1 Accept: application/json RESPONSE HTTP/1.1 200 OK Content-type: application/json Content-length: nnn Location: http://www.example.com/person/123 Etag: 74bef98a330ac {name: “Bob”, age: 25, updated: “2013-01- 31T18:24:36Z”}
  • 18. UPDATE: PUT A RESOURCE REQUEST PUT /person/123 HTTP/1.1 Content-type: application/json Content-length: nnn {name: “Bob”, age: 24} RESPONSE HTTP/1.1 200 OK Content-type: application/json Content-length: nnn Location: http://www.example.com/person/123 Etag: 83c092fdb32b {name: “Bob”, age: 24, updated: “2013-01- 31T18:47:02Z”}
  • 19. DELETE: DELETE A RESOURCE REQUEST DELETE /person/123 HTTP/1.1 DELETE /person/123 HTTP/1.1 Authorization: Basic X738bjNhsk2j== RESPONSE HTTP/1.1 401 Unauthorized WWW-Authenticate: Basic realm=“administration” HTTP/1.1 204 No Content
  • 20. BE CAREFUL WITH BASIC AUTHORIZATION • Basic Authorization passes credentials Base64 encoded • This is easily decoded – equivalent to cleartext! • Fine for toy examples, be careful for production services • Can be OK to use if the service is deployed on SSL • Recommended to consider application-level scheme such as OAuth 2.0 • See the following for more information • http://blog.apigee.com/detail/api_authentication_and_how_ it_got_that_way_from_http_basic_to_oauth_2.0 • http://stackoverflow.com/questions/549/the-definitive- guide-to-forms-based-website-authentication
  • 21. PARTY ON! A RESTFUL SERVICE IN PRACTICE
  • 22. GEARBOX HOLIDAY PARTY For the past few years, the party features an extended presentation that the partygoers watch as gifts are awarded For 2012, we wanted to extend this with some interactivity The idea was born to allow participants to vote on their smartphones by building a companion app • Ugly Christmas Sweater Contest • White Elephant – Choose Their Fate The companion app tabulates votes via RESTful service The presentation asks the service for the results in real-time
  • 24. Splash screen while voting is closed COMPANION APP
  • 25. The ballot is not yet open for voting PRESENTATION
  • 26. Voting is happening on the Companion App PRESENTATION
  • 27. Participants can tap on sweaters any number of times to vote COMPANION APP
  • 28. Polls closed, winner chosen PRESENTATION
  • 29. White Elephant voting is in progress PRESENTATION
  • 30. Participants can tap on words any number of times to vote COMPANION APP
  • 32. Ballots defined, CRUD operations, controls to manually activate & deactivate SERVICE ADMINISTRATION http://partyservice/ballots
  • 33. Choices defined, CRUD operations SERVICE ADMINISTRATION http://partyservice/ballot/1/choices
  • 34. Edit a choice, view the choice SERVICE ADMINISTRATION http://partyservice/ballot/1/choice/2
  • 35. Entrants defined, CRUD operations SERVICE ADMINISTRATION http://partyservice/entrants
  • 36. Edit an entrant, view an entrant SERVICE ADMINISTRATION http://partyservice/entrant/3
  • 38. IMPLEMENTING A RESOURCE Examples are in Ruby 1.9 with Rails 3.2 The principles apply to any RESTful design, irrespective of language and framework First we will look at the routes which define resources Then we will see CRUD operations implemented along with a special custom action Finally we will bring it all together in the companion app and the presentation
  • 39. Defines Resources and provides a means to access them via HTTP verbs ROUTES: THE HEART OF THE SERVICE
  • 40. This method supports JSON encoding and creates a ballot from the POST body CREATE BALLOT
  • 41. This method displays a ballot either in HTML for the admin UI, or JSON for the app READ BALLOT
  • 42. This method reads the JSON ballot, saves it, then renders again in desired format UPDATE BALLOT
  • 43. This method deletes a ballot. In the admin UI, it redirects to the ballot listing DELETE BALLOT
  • 44. Not 100% RESTful, but a convenient pattern to add another verb CUSTOM METHOD: ACTIVATE
  • 45. Also not 100% RESTful, this method records a vote CUSTOM METHOD: RECORD VOTE
  • 46. JavaScript in the browser loads choices from the service, inspecting JSON result APP: LOAD CHOICES
  • 47. JavaScript in the browser sends votes to a custom action APP: VOTE ON A CHOICE
  • 48. Presentation ActionScript prefetches the ballot, choices, and images (HTTP GET) PRESENTATION: PREFETCH
  • 49. Presentation ActionScript activates a ballot to open the polls (HTTP POST) PRESENTATION: ACTIVATE BALLOT
  • 50. Presentation ActionScript requests results in real-time (HTTP GET) PRESENTATION: GET RESULTS
  • 52. RESULTS! The party service, app, and presentation were a big hit We processed over 50,000 votes in approximately 10 minutes Partygoers reported they really enjoyed the experience Future work: • More interactivity • Mini-game?
  • 53. PARTING THOUGHTS RESTful Web Services are great because they are a simple way to take advantage of the whole web pipeline There are some downsides • Ad-hoc implementations mean little guidance, especially on crucial topics like security and I18N • There’s not necessarily one way to do things • May need to roll-your-own connections to services from different vendors Embrace the architecture, be pragmatic Build a companion app that pushes the boundary Have fun!
  • 54. ADDITIONAL RESOURCES Sun Cloud API exploration http://kenai.com/projects/suncloudapis/pages/HelloCloud REST Anti-Patterns http://www.infoq.com/articles/rest-anti-patterns RESTFul Web Services Leonard Richardson, Sam Ruby O'Reilly Media, May 2007 Jimmy Sieben Lead Programmer, Gearbox Software Twitter: @jimmys jimmy.sieben@gearboxsoftware.com

Notes de l'éditeur

  1. Client–server A uniform interface separates clients from servers. This separation of concerns means that, for example, clients are not concerned with data storage, which remains internal to each server, so that the portability of client code is improved. Servers are not concerned with the user interface or user state, so that servers can be simpler and more scalable. Servers and clients may also be replaced and developed independently, as long as the interface between them is not altered. Stateless The client–server communication is further constrained by no client context being stored on the server between requests. Each request from any client contains all of the information necessary to service the request, and any session state is held in the client. Cacheable As on the World Wide Web, clients can cache responses. Responses must therefore, implicitly or explicitly, define themselves as cacheable, or not, to prevent clients reusing stale or inappropriate data in response to further requests. Well-managed caching partially or completely eliminates some client–server interactions, further improving scalability and performance. Layered system A client cannot ordinarily tell whether it is connected directly to the end server, or to an intermediary along the way. Intermediary servers may improve system scalability by enabling load-balancing and by providing shared caches. They may also enforce security policies. Code on demand (optional) Servers are able to temporarily extend or customize the functionality of a client by the transfer of executable code. Examples of this may include compiled components such as Java applets and client-side scripts such as JavaScript. Uniform interface The uniform interface between clients and servers, discussed below, simplifies and decouples the architecture, which enables each part to evolve independently. The four guiding principles of this interface are detailed below.
  2. Identification of resources Individual resources are identified in requests, for example using URIs in web-based REST systems. The resources themselves are conceptually separate from the representations that are returned to the client. For example, the server does not send its database, but rather, perhaps, some HTML, XML or JSON that represents some database records expressed, for instance, in Swahili and encoded in UTF-8, depending on the details of the request and the server implementation. Manipulation of resources through these representations When a client holds a representation of a resource, including any metadata attached, it has enough information to modify or delete the resource on the server, provided it has permission to do so. Self-descriptive messages Each message includes enough information to describe how to process the message. For example, which parser to invoke may be specified by an Internet media type (previously known as a MIME type). Responses also explicitly indicate their cacheability.[1] Hypermedia as the engine of application state (aka HATEOAS) Clients make state transitions only through actions that are dynamically identified within hypermedia by the server (e.g., by hyperlinks within hypertext). Except for simple fixed entry points to the application, a client does not assume that any particular action is available for any particular resources beyond those described in representations previously received from the server.