SlideShare uma empresa Scribd logo
1 de 21
Baixar para ler offline
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!

Mais conteúdo relacionado

Mais procurados

Working with web_services
Working with web_servicesWorking with web_services
Working with web_servicesLorna Mitchell
 
Http programming in play
Http programming in playHttp programming in play
Http programming in playKnoldus Inc.
 
Ground Control to Nomad Job Dispatch
Ground Control to Nomad Job DispatchGround Control to Nomad Job Dispatch
Ground Control to Nomad Job DispatchMichael Lange
 
4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebookguoqing75
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with ExpressAaron Stannard
 
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 CLIAmazon Web Services
 
Zend Framework Study@Tokyo vol1
Zend Framework Study@Tokyo vol1Zend Framework Study@Tokyo vol1
Zend Framework Study@Tokyo vol1Shinya Ohyanagi
 
Redis for your boss 2.0
Redis for your boss 2.0Redis for your boss 2.0
Redis for your boss 2.0Elena Kolevska
 
Cape Cod Web Technology Meetup - 2
Cape Cod Web Technology Meetup - 2Cape Cod Web Technology Meetup - 2
Cape Cod Web Technology Meetup - 2Asher Martin
 
Php basic for vit university
Php basic for vit universityPhp basic for vit university
Php basic for vit universityMandakini Kumari
 
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 CLIDanilo Poccia
 
Using the new WordPress REST API
Using the new WordPress REST APIUsing the new WordPress REST API
Using the new WordPress REST APICaldera Labs
 
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 StyleDaniel-Constantin Mierla
 
Umleitung: a tiny mochiweb/CouchDB app
Umleitung: a tiny mochiweb/CouchDB appUmleitung: a tiny mochiweb/CouchDB app
Umleitung: a tiny mochiweb/CouchDB appLenz Gschwendtner
 
Rails2 Pr
Rails2 PrRails2 Pr
Rails2 Prxibbar
 

Mais procurados (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
 

Semelhante a Spray human talks

spray: REST on Akka
spray: REST on Akkaspray: REST on Akka
spray: REST on Akkasirthias
 
Scala45 spray test
Scala45 spray testScala45 spray test
Scala45 spray testkopiczko
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.pptWalaSidhom1
 
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-rsSagara Gunathunga
 
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 HTTPdatamantra
 
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 Pythonkwatch
 
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 EXPRESSannalakshmi35
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSam Brannen
 
The Functional Web
The Functional WebThe Functional Web
The Functional WebRyan Riley
 
Introduction to rest using flask
Introduction to rest using flaskIntroduction to rest using flask
Introduction to rest using flaskWekanta
 
iOS Reactive Cocoa Pipeline
iOS Reactive Cocoa PipelineiOS Reactive Cocoa Pipeline
iOS Reactive Cocoa PipelineIvan Trifonov
 
Web program-peformance-optimization
Web program-peformance-optimizationWeb program-peformance-optimization
Web program-peformance-optimizationxiaojueqq12345
 
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 easeKAI CHU CHUNG
 
Server Side Swift with Swag
Server Side Swift with SwagServer Side Swift with Swag
Server Side Swift with SwagJens Ravens
 
API Testing. Streamline your testing process.
API Testing. Streamline your testing process.API Testing. Streamline your testing process.
API Testing. Streamline your testing process.Andrey Oleynik
 

Semelhante 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

"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 

Último (20)

"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 

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