SlideShare une entreprise Scribd logo
1  sur  21
Télécharger pour lire hors ligne
REST on Akka	

!

Antoine Comte	

Twitter : @comte_a	

antoine.comte@gmail.com	

Slidedeck courtesy of the Spray team
What is spray?
Suite of libraries for building and consuming
RESTful web services on top of Akka	


• First released about 2 year ago	

• Principles: lightweight, async, non-blocking,
actor-based, modular, few deps, testable	


• Philosophy: library, not framework
Components
• Rich immutable HTTP model	

• spray-server:


DSL for server-side API construction	


• spray-client: complementary HTTP client 	

• spray-can: low-level HTTP server and client	

• spray-json: straight JSON in scala (no Akka)
spray-server
• Runs on servlet containers or spray-can	

• Tool for building a “self-contained” API layer	

• Central element:

Routing DSL for defining web API behavior	


• Focus: RESTful web API, not web GUI
Basic Architecture
Application

Business	

Logic
Basic Architecture
REST API layer

Application

HTTP Request

Routing	

Logic

Business	

Logic
Basic Architecture
REST API layer

HTTP Request

Action

Routing	

Logic

HTTP Response

Application

domain
object !
Reply

Business	

Logic
API Layer Responsibilities
• Request routing based on method, path,
query parameters, entity	


• (Un)marshalling to / from domain objects	

• Encoding / decoding	

• Authentication / authorization	

• Caching and serving static content	

• RESTful error handling
Route Example
A simple spray route:	

!

val route: Route =
path("order" / HexIntNumber) { id =>
get {
completeWith {
"Received GET request for order " + id
}
} ~
put {
completeWith {
"Received PUT request for order " + id
}
}
}
Routing Basics
Routes in spray:	

type Route = RequestContext => Unit

!

Central object:	

case class RequestContext(
request: HttpRequest,
...) {
  def complete(...) { ... }
  def reject(...) { ... }
  ...
}

Explicit
continuation-

passing style
Routing Basics
The simplest route:	

ctx => ctx.complete("Say hello to spray")

or:	

_.complete("Say hello to spray")

or using a “directive”:	

completeWith("Say hello to spray")
def completeWith[T :Marshaller](value: => T): Route =
_.complete(value)
Directives
Route structure built with directives:	

!

val route: Route =
path("order" / HexIntNumber) { id =>
get {
completeWith {
"Received GET request for order " + id
}
} ~
put {
completeWith {
"Received PUT request for order " + id
}
}
}

extractions

directive
name

args
route concatenation:
recover from rejections
Route structure
forms a tree!

inner route
Directives
Compiles?

Operators are type-safe:	

val orderPath = path("order" / IntNumber)
val dir = orderPath | get
val dir = orderPath | path("[^/]+".r / DoubleNumber)
val dir = orderPath | parameter('order.as[Int])
val order = orderPath & parameters('oem, 'expired ?)
val route = order { (orderId, oem, expired) =>
... // inner route
}
Directives



spray 1.2 comes with 110 predefined directives:

alwaysCache, anyParam, anyParams, authenticate, authorize, autoChunk, cache, cachingProhibited,
cancelAllRejections, cancelRejection, clientIP, complete, compressResponse,
compressResponseIfRequested, cookie, decodeRequest, decompressRequest, delete, deleteCookie,
detach, dynamic, dynamicIf, encodeResponse, entity, extract, failWith, formField, formFields, get,
getFromBrowseableDirectories, getFromBrowseableDirectory, getFromDirectory, getFromFile,
getFromResource, getFromResourceDirectory, handleExceptions, handleRejections, handleWith, head,
headerValue, headerValueByName, headerValuePF, hextract, host, hostName, hprovide,
jsonpWithParameter, listDirectoryContents, logRequest, logRequestResponse, logResponse,
mapHttpResponse, mapHttpResponsePart, mapHttpResponseEntity, mapHttpResponseHeaders,
mapInnerRoute, mapRejections, mapRequest, mapRequestContext, mapRouteResponse,
mapRouteResponsePF, method, overrideMethodWithParameter, noop, onComplete, onFailure,
onSuccess, optionalCookie, optionalHeaderValue, optionalHeaderValueByName,
optionalHeaderValuePF, options, parameter, parameterMap, parameterMultiMap, parameters,
parameterSeq, pass, patch, path, pathPrefix, pathPrefixTest, pathSuffix, pathSuffixTest, post, produce,
provide, put, redirect, reject, rejectEmptyResponse, requestEncodedWith, requestEntityEmpty,
requestEntityPresent, respondWithHeader, respondWithHeaders, respondWithLastModifiedHeader,
respondWithMediaType, respondWithSingletonHeader, respondWithSingletonHeaders,
respondWithStatus, responseEncodingAccepted, rewriteUnmatchedPath, routeRouteResponse,
scheme, schemeName, setCookie, unmatchedPath, validate
Real World Example
lazy val route = {
encodeResponse(Gzip) {
path("") {
get {
redirect("/doc")
}
} ~
pathPrefix("api") {
jsonpWithParameter("callback") {
path("top-articles") {
get {
parameter('max.as[Int]) { max =>
validate(max >= 0, "query parameter 'max' must be >= 0") {
completeWith {
(topArticlesService ? max).mapTo[Seq[Article]]
}
}
}
}
} ~
tokenAuthenticate { user =>
path("ranking") {
get {
countAndTime(user, "ranking") {
parameters('fixed ? 0, 'mobile ? 0, 'sms ? 0, 'mms ? 0,
Best Practices
• Keep route structure clean and readable,

pull out all logic into custom directives	


• Don’t let API layer leak into application	

• Use (Un)marshalling infrastructure	

• Wrap blocking code with `detach`	

• Use sbt-revolver + JRebel for fast dev turnaround
There is more ...
• SprayJsonSupport, LiftJsonSupport,
TwirlSupport, ScalateSupport	


• Asynchronous response push streaming	

• Testing spray routes	

• RESTful errors	

• spray-client
Current State
• spray 1.2-RC2 just released

• Coming features: new documentation site,
deeper REST support, monitoring, request
throttling, and more ...
A few current sprayers ...
Getting started
• Main site & documentation:

http://spray.io/	


• Mailing list:


http://groups.google.com/group/spray-user	


• Twitter:


@sprayio
Thank you!

Contenu connexe

Tendances

Working with web_services
Working with web_servicesWorking with web_services
Working with web_services
Lorna Mitchell
 
4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook
guoqing75
 
Zend Framework Study@Tokyo vol1
Zend Framework Study@Tokyo vol1Zend Framework Study@Tokyo vol1
Zend Framework Study@Tokyo vol1
Shinya Ohyanagi
 

Tendances (20)

Working with web_services
Working with web_servicesWorking with web_services
Working with web_services
 
Http programming in play
Http programming in playHttp programming in play
Http programming in play
 
Ground Control to Nomad Job Dispatch
Ground Control to Nomad Job DispatchGround Control to Nomad Job Dispatch
Ground Control to Nomad Job Dispatch
 
4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with Express
 
Deep Dive - Advanced Usage of the AWS CLI
Deep Dive - Advanced Usage of the AWS CLIDeep Dive - Advanced Usage of the AWS CLI
Deep Dive - Advanced Usage of the AWS CLI
 
Redis for your boss
Redis for your bossRedis for your boss
Redis for your boss
 
Zend Framework Study@Tokyo vol1
Zend Framework Study@Tokyo vol1Zend Framework Study@Tokyo vol1
Zend Framework Study@Tokyo vol1
 
Redis for your boss 2.0
Redis for your boss 2.0Redis for your boss 2.0
Redis for your boss 2.0
 
Cape Cod Web Technology Meetup - 2
Cape Cod Web Technology Meetup - 2Cape Cod Web Technology Meetup - 2
Cape Cod Web Technology Meetup - 2
 
Akka http
Akka httpAkka http
Akka http
 
Php basic for vit university
Php basic for vit universityPhp basic for vit university
Php basic for vit university
 
Masterclass Advanced Usage of the AWS CLI
Masterclass Advanced Usage of the AWS CLIMasterclass Advanced Usage of the AWS CLI
Masterclass Advanced Usage of the AWS CLI
 
Using the new WordPress REST API
Using the new WordPress REST APIUsing the new WordPress REST API
Using the new WordPress REST API
 
Kamailio - Surfing Big Waves Of SIP With Style
Kamailio - Surfing Big Waves Of SIP With StyleKamailio - Surfing Big Waves Of SIP With Style
Kamailio - Surfing Big Waves Of SIP With Style
 
Introduction to Flask Micro Framework
Introduction to Flask Micro FrameworkIntroduction to Flask Micro Framework
Introduction to Flask Micro Framework
 
scalaphx-akka-http
scalaphx-akka-httpscalaphx-akka-http
scalaphx-akka-http
 
Refactoring terraform
Refactoring terraformRefactoring terraform
Refactoring terraform
 
Umleitung: a tiny mochiweb/CouchDB app
Umleitung: a tiny mochiweb/CouchDB appUmleitung: a tiny mochiweb/CouchDB app
Umleitung: a tiny mochiweb/CouchDB app
 
Rails2 Pr
Rails2 PrRails2 Pr
Rails2 Pr
 

Similaire à Spray human talks

nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
WalaSidhom1
 
MERN SRTACK WEB DEVELOPMENT NODE JS EXPRESS
MERN SRTACK WEB DEVELOPMENT NODE JS EXPRESSMERN SRTACK WEB DEVELOPMENT NODE JS EXPRESS
MERN SRTACK WEB DEVELOPMENT NODE JS EXPRESS
annalakshmi35
 

Similaire à Spray human talks (20)

spray: REST on Akka
spray: REST on Akkaspray: REST on Akka
spray: REST on Akka
 
Scala45 spray test
Scala45 spray testScala45 spray test
Scala45 spray test
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
Java colombo-deep-dive-into-jax-rs
Java colombo-deep-dive-into-jax-rsJava colombo-deep-dive-into-jax-rs
Java colombo-deep-dive-into-jax-rs
 
Building scalable rest service using Akka HTTP
Building scalable rest service using Akka HTTPBuilding scalable rest service using Akka HTTP
Building scalable rest service using Akka HTTP
 
How to make the fastest Router in Python
How to make the fastest Router in PythonHow to make the fastest Router in Python
How to make the fastest Router in Python
 
23003468463PPT.pptx
23003468463PPT.pptx23003468463PPT.pptx
23003468463PPT.pptx
 
MERN SRTACK WEB DEVELOPMENT NODE JS EXPRESS
MERN SRTACK WEB DEVELOPMENT NODE JS EXPRESSMERN SRTACK WEB DEVELOPMENT NODE JS EXPRESS
MERN SRTACK WEB DEVELOPMENT NODE JS EXPRESS
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
 
Server Side Swift: Vapor
Server Side Swift: VaporServer Side Swift: Vapor
Server Side Swift: Vapor
 
The Functional Web
The Functional WebThe Functional Web
The Functional Web
 
Rack
RackRack
Rack
 
Introduction to rest using flask
Introduction to rest using flaskIntroduction to rest using flask
Introduction to rest using flask
 
iOS Reactive Cocoa Pipeline
iOS Reactive Cocoa PipelineiOS Reactive Cocoa Pipeline
iOS Reactive Cocoa Pipeline
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
Web program-peformance-optimization
Web program-peformance-optimizationWeb program-peformance-optimization
Web program-peformance-optimization
 
GDG Devfest 2019 - Build go kit microservices at kubernetes with ease
GDG Devfest 2019 - Build go kit microservices at kubernetes with easeGDG Devfest 2019 - Build go kit microservices at kubernetes with ease
GDG Devfest 2019 - Build go kit microservices at kubernetes with ease
 
Server Side Swift with Swag
Server Side Swift with SwagServer Side Swift with Swag
Server Side Swift with Swag
 
From Node to Go
From Node to GoFrom Node to Go
From Node to Go
 
API Testing. Streamline your testing process.
API Testing. Streamline your testing process.API Testing. Streamline your testing process.
API Testing. Streamline your testing process.
 

Dernier

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Dernier (20)

Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 

Spray human talks

  • 1. REST on Akka ! Antoine Comte Twitter : @comte_a antoine.comte@gmail.com Slidedeck courtesy of the Spray team
  • 2. What is spray? Suite of libraries for building and consuming RESTful web services on top of Akka • First released about 2 year ago • Principles: lightweight, async, non-blocking, actor-based, modular, few deps, testable • Philosophy: library, not framework
  • 3. Components • Rich immutable HTTP model • spray-server:
 DSL for server-side API construction • spray-client: complementary HTTP client • spray-can: low-level HTTP server and client • spray-json: straight JSON in scala (no Akka)
  • 4. spray-server • Runs on servlet containers or spray-can • Tool for building a “self-contained” API layer • Central element:
 Routing DSL for defining web API behavior • Focus: RESTful web API, not web GUI
  • 6. Basic Architecture REST API layer Application HTTP Request Routing Logic Business Logic
  • 7. Basic Architecture REST API layer HTTP Request Action Routing Logic HTTP Response Application domain object ! Reply Business Logic
  • 8. API Layer Responsibilities • Request routing based on method, path, query parameters, entity • (Un)marshalling to / from domain objects • Encoding / decoding • Authentication / authorization • Caching and serving static content • RESTful error handling
  • 9. Route Example A simple spray route: ! val route: Route = path("order" / HexIntNumber) { id => get { completeWith { "Received GET request for order " + id } } ~ put { completeWith { "Received PUT request for order " + id } } }
  • 10. Routing Basics Routes in spray: type Route = RequestContext => Unit ! Central object: case class RequestContext( request: HttpRequest, ...) {   def complete(...) { ... }   def reject(...) { ... }   ... } Explicit continuation-
 passing style
  • 11. Routing Basics The simplest route: ctx => ctx.complete("Say hello to spray") or: _.complete("Say hello to spray") or using a “directive”: completeWith("Say hello to spray") def completeWith[T :Marshaller](value: => T): Route = _.complete(value)
  • 12. Directives Route structure built with directives: ! val route: Route = path("order" / HexIntNumber) { id => get { completeWith { "Received GET request for order " + id } } ~ put { completeWith { "Received PUT request for order " + id } } } extractions directive name args route concatenation: recover from rejections Route structure forms a tree! inner route
  • 13. Directives Compiles? Operators are type-safe: val orderPath = path("order" / IntNumber) val dir = orderPath | get val dir = orderPath | path("[^/]+".r / DoubleNumber) val dir = orderPath | parameter('order.as[Int]) val order = orderPath & parameters('oem, 'expired ?) val route = order { (orderId, oem, expired) => ... // inner route }
  • 14. Directives 
 spray 1.2 comes with 110 predefined directives:
 alwaysCache, anyParam, anyParams, authenticate, authorize, autoChunk, cache, cachingProhibited, cancelAllRejections, cancelRejection, clientIP, complete, compressResponse, compressResponseIfRequested, cookie, decodeRequest, decompressRequest, delete, deleteCookie, detach, dynamic, dynamicIf, encodeResponse, entity, extract, failWith, formField, formFields, get, getFromBrowseableDirectories, getFromBrowseableDirectory, getFromDirectory, getFromFile, getFromResource, getFromResourceDirectory, handleExceptions, handleRejections, handleWith, head, headerValue, headerValueByName, headerValuePF, hextract, host, hostName, hprovide, jsonpWithParameter, listDirectoryContents, logRequest, logRequestResponse, logResponse, mapHttpResponse, mapHttpResponsePart, mapHttpResponseEntity, mapHttpResponseHeaders, mapInnerRoute, mapRejections, mapRequest, mapRequestContext, mapRouteResponse, mapRouteResponsePF, method, overrideMethodWithParameter, noop, onComplete, onFailure, onSuccess, optionalCookie, optionalHeaderValue, optionalHeaderValueByName, optionalHeaderValuePF, options, parameter, parameterMap, parameterMultiMap, parameters, parameterSeq, pass, patch, path, pathPrefix, pathPrefixTest, pathSuffix, pathSuffixTest, post, produce, provide, put, redirect, reject, rejectEmptyResponse, requestEncodedWith, requestEntityEmpty, requestEntityPresent, respondWithHeader, respondWithHeaders, respondWithLastModifiedHeader, respondWithMediaType, respondWithSingletonHeader, respondWithSingletonHeaders, respondWithStatus, responseEncodingAccepted, rewriteUnmatchedPath, routeRouteResponse, scheme, schemeName, setCookie, unmatchedPath, validate
  • 15. Real World Example lazy val route = { encodeResponse(Gzip) { path("") { get { redirect("/doc") } } ~ pathPrefix("api") { jsonpWithParameter("callback") { path("top-articles") { get { parameter('max.as[Int]) { max => validate(max >= 0, "query parameter 'max' must be >= 0") { completeWith { (topArticlesService ? max).mapTo[Seq[Article]] } } } } } ~ tokenAuthenticate { user => path("ranking") { get { countAndTime(user, "ranking") { parameters('fixed ? 0, 'mobile ? 0, 'sms ? 0, 'mms ? 0,
  • 16. Best Practices • Keep route structure clean and readable,
 pull out all logic into custom directives • Don’t let API layer leak into application • Use (Un)marshalling infrastructure • Wrap blocking code with `detach` • Use sbt-revolver + JRebel for fast dev turnaround
  • 17. There is more ... • SprayJsonSupport, LiftJsonSupport, TwirlSupport, ScalateSupport • Asynchronous response push streaming • Testing spray routes • RESTful errors • spray-client
  • 18. Current State • spray 1.2-RC2 just released
 • Coming features: new documentation site, deeper REST support, monitoring, request throttling, and more ...
  • 19. A few current sprayers ...
  • 20. Getting started • Main site & documentation:
 http://spray.io/ • Mailing list:
 http://groups.google.com/group/spray-user • Twitter:
 @sprayio