SlideShare una empresa de Scribd logo
1 de 21
Descargar para leer sin conexión
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!

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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
 

Similar a 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
 

Similar a 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.
 

Último

+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)

Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
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
 
+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...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
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
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
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
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 

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