WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
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”}
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
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
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
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
Editor's Notes
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.
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.