SlideShare a Scribd company logo
AKKA HTTP
A.K.A. SPRAY 2.0
Présenté par Jean Detoeuf / @thebignet
JEAN DETOEUF
DÉVELOPPEUR
Passionné de nouvelles technologies
#jvm #docker #craftmanship #rpi #diy
AVERTISSEMENT
Je ne suis pas un expert en Scala
Soyez sympas ^^
PROJET EN COURS DE MATURATION
version lors de cette présentation2.0.1
mélange entre Spray et Akka
J'ai eu l'idée de cette présentation à la version 1.0, il était temps !
AKKA STREAMS
Présenté au SLUG par en février 2015Frédéric Masion
Source ~> Flow ~> Sink
Source décrit une source de données
Flow représente une transformation de ces données
Sink une opération terminale
AKKA STREAMS
Source ~> Flow1 ~> Flow2a ~> Sink
~> Flow2b
Fan-out / Fan-in
AKKA HTTP
Constuit sur Akka Streams
Internet est un tuyau
rempli de chatons
AKKA HTTP
Flow[HttpRequest, HttpResponse]
AKKA HTTP
Client et serveur
Mettre des acteurs sur HTTP
MODULES
akka-http-spray-json
akka-http-xml
akka-http-testkit
akka-http
akka-http-core
C'EST BON, MONTRE-MOI LE CODE
Les exemples sont pour la plupart tirés de la documentation
d'Akka
EXEMPLE SIMPLE
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport._
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
object Main extends App {
implicit val system = ActorSystem("my-system")
implicit val materializer = ActorMaterializer()
implicit val ec = system.dispatcher
val route =
path("hello") {
get {
complete {
<h1>Say hello to akka-http</h1>
}
}
}
val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)
println(s"Server online at http://localhost:8080/nPress RETURN to stop...")
Console.readLine() // for the future transformations
bindingFuture
.flatMap(_.unbind()) // trigger unbinding from the port
.onComplete(_ ⇒ system.shutdown()) // and shutdown when done
}
EXEMPLE SIMPLE
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport._
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
object Main extends App {
implicit val system = ActorSystem("my-system")
implicit val materializer = ActorMaterializer()
implicit val ec = system.dispatcher
val route =
path("hello") {
get {
complete {
<h1>Say hello to akka-http</h1>
}
}
}
val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)
println(s"Server online at http://localhost:8080/nPress RETURN to stop...")
Console.readLine() // for the future transformations
bindingFuture
.flatMap(_.unbind()) // trigger unbinding from the port
.onComplete(_ ⇒ system.shutdown()) // and shutdown when done
}
EXEMPLE SIMPLE
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport._
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
object Main extends App {
implicit val system = ActorSystem("my-system")
implicit val materializer = ActorMaterializer()
implicit val ec = system.dispatcher
val route =
path("hello") {
get {
complete {
<h1>Say hello to akka-http</h1>
}
}
}
val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)
println(s"Server online at http://localhost:8080/nPress RETURN to stop...")
Console.readLine() // for the future transformations
bindingFuture
.flatMap(_.unbind()) // trigger unbinding from the port
.onComplete(_ ⇒ system.shutdown()) // and shutdown when done
}
EXEMPLE SIMPLE
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport._
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
object Main extends App {
implicit val system = ActorSystem("my-system")
implicit val materializer = ActorMaterializer()
implicit val ec = system.dispatcher
val route =
path("hello") {
get {
complete {
<h1>Say hello to akka-http</h1>
}
}
}
val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)
println(s"Server online at http://localhost:8080/nPress RETURN to stop...")
Console.readLine() // for the future transformations
bindingFuture
.flatMap(_.unbind()) // trigger unbinding from the port
.onComplete(_ ⇒ system.shutdown()) // and shutdown when done
}
MARSHALLING/UNMARSHALLING
MARSHALLING/UNMARSHALLING
Comment passer d'un flux HTTP à Scala et inversement ?
MARSHALLING
Marshallers prédéfinis
Array[Byte]
ByteString
Array[Char]
String
akka.http.scaladsl.model.FormData
akka.http.scaladsl.model.MessageEntity
T <: akka.http.scaladsl.model.Multipart
T si ToEntityMarshaller[T] est présent
MARSHALLING
Résolution implicite
Si le type ToEntityMarshaller[T] est défini, il est utilisé
UNMARSHALLING
Unmarshallers prédéfinis
Byte
Short
Int
Long
Float
Double
Boolean
Array[Byte]
ByteString
Array[Char]
String
akka.http.scaladsl.model.FormData
ROUTAGE
LOW-LEVEL
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model._
import akka.stream.ActorMaterializer
implicit val system = ActorSystem()
implicit val materializer = ActorMaterializer()
val requestHandler: HttpRequest => HttpResponse = {
case HttpRequest(GET, Uri.Path("/"), _, _, _) =>
HttpResponse(entity = HttpEntity(ContentTypes.`text/html(UTF-8)`
,
"Hello world!"))
case HttpRequest(GET, Uri.Path("/ping"), _, _, _) =>
HttpResponse(entity = "PONG!")
case HttpRequest(GET, Uri.Path("/crash"), _, _, _) =>
sys.error("BOOM!")
case _: HttpRequest =>
HttpResponse(404, entity = "Unknown resource!")
}
Http().bindAndHandleSync(requestHandler, "localhost", 8080)
HIGH-LEVEL
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport._
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
implicit val system = ActorSystem()
implicit val materializer = ActorMaterializer()
val route =
get {
pathSingleSlash {
complete {
<html>
<body>Hello world!</body>
</html>
}
} ~
path("ping") {
complete("PONG!")
} ~
path("crash") {
sys.error("BOOM!")
}
}
// `route` will be implicitly converted to `Flow` using `RouteResult
.route2HandlerFlow`
Http().bindAndHandle(route, "localhost", 8080)
DIRECTIVES
DIRECTIVES
Intercepte la requête
Filtrage de la requête
Transformation de la requête ou réponse
Extraire des informations
EXEMPLE
val route =
path("order" / IntNumber) { id =>
(get | put) {
extractMethod { m =>
complete(s"Received ${m.name} request for order $id")
}
}
}
EXEMPLE 2
val orderGetOrPutWithMethod =
path("order" / IntNumber) & (get | put) & extractMethod
val route = orderGetOrPutWithMethod { (id, m) =>
complete(s"Received ${m.name} request for order $id")
}
et
PATHMATCHER
val matcher: PathMatcher1[Option[Int]] =
"foo" / "bar" / "X" ~ IntNumber.? / ("edit" | "create")
Intercepte les chemins suivants :
foo/bar/X42/edit
foo/bar/X/create
EXTRACTION CASE CLASS
case class Color(red: Int, green: Int, blue: Int)
val route = path("color") {
parameters('red.as[Int], 'green.as[Int], 'blue.as[Int]).as(Color)
{
color =>
// utiliser color
}
}
VALIDATION CASE CLASS
case class Color(name: String, red: Int, green: Int, blue: Int) {
require(!name.isEmpty, "color name must not be empty")
require(0 <= red && red <= 255, "red color component must be betwe
en 0 and 255")
require(0 <= green && green <= 255, "green color component must be
between 0 and 255")
require(0 <= blue && blue <= 255, "blue color component must be be
tween 0 and 255")
}
ValidationRejection si require ne passe pas
Par défaut : 400 Bad Request
TESTS
Pour la route suivante
val smallRoute =
get {
pathSingleSlash {
complete {
"Hello World !"
}
} ~
path("ping") {
complete("PONG !")
}
}
Test
"Hello World ! non renvoyé sur /" in {
Get() ~> smallRoute ~> check {
status === StatusCodes.OK
responseAs[String] shouldEqual "Hello World !"
}
}
Pour la même route ...
val smallRoute =
get {
pathSingleSlash {
complete {
"Hello World !"
}
} ~
path("ping") {
complete("PONG !")
}
}
Test
"GET sur chemin inconnu non pris en compte" in {
Get("/pouet") ~> smallRoute ~> check {
handled shouldBe false
}
}
VARIABLES UTILISABLES DANS LES
TESTS
entityAs
handled
header
response
status
entre autres ...
CLIENT
val responseFuture: Future[HttpResponse] =
Http().singleRequest(HttpRequest(uri = "http://akka.io"))
QUESTIONS ?
MERCI POUR VOTRE ÉCOUTE
Cette présentation :
@thebignet
thebignet
thebignet
talk-akka-http

More Related Content

ODP
Akka http
ODP
An Introduction to Akka http
PDF
scalaphx-akka-http
PDF
Practical Akka HTTP - introduction
PDF
Building scalable rest service using Akka HTTP
PDF
Akka Http , Routes, Streams with Scala
ODP
Http programming in play
PDF
Display earthquakes with Akka-http
Akka http
An Introduction to Akka http
scalaphx-akka-http
Practical Akka HTTP - introduction
Building scalable rest service using Akka HTTP
Akka Http , Routes, Streams with Scala
Http programming in play
Display earthquakes with Akka-http

What's hot (20)

PDF
Akka Streams and HTTP
PDF
Journey into Reactive Streams and Akka Streams
PPTX
Apache Apex - BufferServer
PDF
VJUG24 - Reactive Integrations with Akka Streams
PDF
Scala usergroup stockholm - reactive integrations with akka streams
PPTX
Developing distributed applications with Akka and Akka Cluster
PDF
System Integration with Akka and Apache Camel
PDF
Service discovery like a pro (presented at reversimX)
PDF
Asynchronous stream processing with Akka Streams
PDF
Introduction tomcat7 servlet3
PDF
Understanding Akka Streams, Back Pressure, and Asynchronous Architectures
PDF
Play Framework
PDF
Reactive Stream Processing with Akka Streams
PDF
Securing Microservices using Play and Akka HTTP
ZIP
Above the clouds: introducing Akka
PPTX
Exploring Twitter's Finagle technology stack for microservices
PDF
Reactive Streams / Akka Streams - GeeCON Prague 2014
PPTX
Stream processing from single node to a cluster
PDF
Reactive integrations with Akka Streams
PDF
Catalyst MVC
Akka Streams and HTTP
Journey into Reactive Streams and Akka Streams
Apache Apex - BufferServer
VJUG24 - Reactive Integrations with Akka Streams
Scala usergroup stockholm - reactive integrations with akka streams
Developing distributed applications with Akka and Akka Cluster
System Integration with Akka and Apache Camel
Service discovery like a pro (presented at reversimX)
Asynchronous stream processing with Akka Streams
Introduction tomcat7 servlet3
Understanding Akka Streams, Back Pressure, and Asynchronous Architectures
Play Framework
Reactive Stream Processing with Akka Streams
Securing Microservices using Play and Akka HTTP
Above the clouds: introducing Akka
Exploring Twitter's Finagle technology stack for microservices
Reactive Streams / Akka Streams - GeeCON Prague 2014
Stream processing from single node to a cluster
Reactive integrations with Akka Streams
Catalyst MVC
Ad

Viewers also liked (20)

PPTX
Building a Reactive RESTful API with Akka Http & Slick
PPTX
Akka-http
PPTX
Akka HTTP
PDF
Akka in Production - ScalaDays 2015
PDF
Scala, Akka, and Play: An Introduction on Heroku
PDF
[Start] Playing
PDF
Playing with Scala
PDF
DUMP-2015: «Распределенная обработка миллионов документов на Scala и Akka» Ст...
ODP
Play Template Engine Based On Scala
PDF
Designing Reactive Systems with Akka
PDF
HTML5 with Play Scala, CoffeeScript and Jade - Devoxx 2011
PDF
Your First Scala Web Application using Play 2.1
PDF
Custom deployments with sbt-native-packager
PDF
Unsucking Error Handling with Futures
PDF
Auto-scaling your API: Insights and Tips from the Zalando Team
PDF
Ship your Scala code often and easy with Docker
PDF
Play framework And Google Cloud Platform GCP.
PPTX
Play! Framework for JavaEE Developers
PDF
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVM
PPTX
Введение в Akka
Building a Reactive RESTful API with Akka Http & Slick
Akka-http
Akka HTTP
Akka in Production - ScalaDays 2015
Scala, Akka, and Play: An Introduction on Heroku
[Start] Playing
Playing with Scala
DUMP-2015: «Распределенная обработка миллионов документов на Scala и Akka» Ст...
Play Template Engine Based On Scala
Designing Reactive Systems with Akka
HTML5 with Play Scala, CoffeeScript and Jade - Devoxx 2011
Your First Scala Web Application using Play 2.1
Custom deployments with sbt-native-packager
Unsucking Error Handling with Futures
Auto-scaling your API: Insights and Tips from the Zalando Team
Ship your Scala code often and easy with Docker
Play framework And Google Cloud Platform GCP.
Play! Framework for JavaEE Developers
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVM
Введение в Akka
Ad

Similar to Akka http 2 (20)

PDF
Rest with-spray
PDF
Spray human talks
PDF
Building REST API using Akka HTTP with Scala
ZIP
spray: REST on Akka
PPTX
Developing a Real-time Engine with Akka, Cassandra, and Spray
PDF
Akka streams - Umeå java usergroup
PDF
Reactive stream processing using Akka streams
KEY
Scalalable Language for a Scalable Web
PDF
Scalatra 2.2
PDF
Akka in Action 1st Edition Raymond Roestenburg download pdf
PDF
Exploring Reactive Integrations With Akka Streams, Alpakka And Apache Kafka
PDF
[PDF Download] Akka in Action 1st Edition Raymond Roestenburg fulll chapter
PDF
## Introducing a reactive Scala-Akka based system in a Java centric company
KEY
spray: REST on Akka (Scala Days)
PDF
Reactive streams processing using Akka Streams
ODP
Spray - Build RESTfull services in scala
PDF
Ratpack Web Framework
PPT
Play!ng with scala
PPTX
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
ODP
Rest with-spray
Spray human talks
Building REST API using Akka HTTP with Scala
spray: REST on Akka
Developing a Real-time Engine with Akka, Cassandra, and Spray
Akka streams - Umeå java usergroup
Reactive stream processing using Akka streams
Scalalable Language for a Scalable Web
Scalatra 2.2
Akka in Action 1st Edition Raymond Roestenburg download pdf
Exploring Reactive Integrations With Akka Streams, Alpakka And Apache Kafka
[PDF Download] Akka in Action 1st Edition Raymond Roestenburg fulll chapter
## Introducing a reactive Scala-Akka based system in a Java centric company
spray: REST on Akka (Scala Days)
Reactive streams processing using Akka Streams
Spray - Build RESTfull services in scala
Ratpack Web Framework
Play!ng with scala
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...

Recently uploaded (20)

PPTX
Introduction to Artificial Intelligence
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PPTX
ISO 45001 Occupational Health and Safety Management System
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
medical staffing services at VALiNTRY
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Digital Strategies for Manufacturing Companies
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PPTX
Transform Your Business with a Software ERP System
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PPTX
Odoo POS Development Services by CandidRoot Solutions
PPTX
ManageIQ - Sprint 268 Review - Slide Deck
Introduction to Artificial Intelligence
Design an Analysis of Algorithms II-SECS-1021-03
ISO 45001 Occupational Health and Safety Management System
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
VVF-Customer-Presentation2025-Ver1.9.pptx
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
medical staffing services at VALiNTRY
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Digital Strategies for Manufacturing Companies
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PTS Company Brochure 2025 (1).pdf.......
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Transform Your Business with a Software ERP System
CHAPTER 2 - PM Management and IT Context
Odoo Companies in India – Driving Business Transformation.pdf
2025 Textile ERP Trends: SAP, Odoo & Oracle
Odoo POS Development Services by CandidRoot Solutions
ManageIQ - Sprint 268 Review - Slide Deck

Akka http 2

  • 1. AKKA HTTP A.K.A. SPRAY 2.0 Présenté par Jean Detoeuf / @thebignet
  • 2. JEAN DETOEUF DÉVELOPPEUR Passionné de nouvelles technologies #jvm #docker #craftmanship #rpi #diy
  • 3. AVERTISSEMENT Je ne suis pas un expert en Scala Soyez sympas ^^
  • 4. PROJET EN COURS DE MATURATION version lors de cette présentation2.0.1 mélange entre Spray et Akka J'ai eu l'idée de cette présentation à la version 1.0, il était temps !
  • 5. AKKA STREAMS Présenté au SLUG par en février 2015Frédéric Masion Source ~> Flow ~> Sink Source décrit une source de données Flow représente une transformation de ces données Sink une opération terminale
  • 6. AKKA STREAMS Source ~> Flow1 ~> Flow2a ~> Sink ~> Flow2b Fan-out / Fan-in
  • 7. AKKA HTTP Constuit sur Akka Streams Internet est un tuyau rempli de chatons
  • 9. AKKA HTTP Client et serveur Mettre des acteurs sur HTTP
  • 11. C'EST BON, MONTRE-MOI LE CODE Les exemples sont pour la plupart tirés de la documentation d'Akka
  • 12. EXEMPLE SIMPLE import akka.http.scaladsl.Http import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport._ import akka.http.scaladsl.server.Directives._ import akka.stream.ActorMaterializer object Main extends App { implicit val system = ActorSystem("my-system") implicit val materializer = ActorMaterializer() implicit val ec = system.dispatcher val route = path("hello") { get { complete { <h1>Say hello to akka-http</h1> } } } val bindingFuture = Http().bindAndHandle(route, "localhost", 8080) println(s"Server online at http://localhost:8080/nPress RETURN to stop...") Console.readLine() // for the future transformations bindingFuture .flatMap(_.unbind()) // trigger unbinding from the port .onComplete(_ ⇒ system.shutdown()) // and shutdown when done }
  • 13. EXEMPLE SIMPLE import akka.http.scaladsl.Http import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport._ import akka.http.scaladsl.server.Directives._ import akka.stream.ActorMaterializer object Main extends App { implicit val system = ActorSystem("my-system") implicit val materializer = ActorMaterializer() implicit val ec = system.dispatcher val route = path("hello") { get { complete { <h1>Say hello to akka-http</h1> } } } val bindingFuture = Http().bindAndHandle(route, "localhost", 8080) println(s"Server online at http://localhost:8080/nPress RETURN to stop...") Console.readLine() // for the future transformations bindingFuture .flatMap(_.unbind()) // trigger unbinding from the port .onComplete(_ ⇒ system.shutdown()) // and shutdown when done }
  • 14. EXEMPLE SIMPLE import akka.http.scaladsl.Http import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport._ import akka.http.scaladsl.server.Directives._ import akka.stream.ActorMaterializer object Main extends App { implicit val system = ActorSystem("my-system") implicit val materializer = ActorMaterializer() implicit val ec = system.dispatcher val route = path("hello") { get { complete { <h1>Say hello to akka-http</h1> } } } val bindingFuture = Http().bindAndHandle(route, "localhost", 8080) println(s"Server online at http://localhost:8080/nPress RETURN to stop...") Console.readLine() // for the future transformations bindingFuture .flatMap(_.unbind()) // trigger unbinding from the port .onComplete(_ ⇒ system.shutdown()) // and shutdown when done }
  • 15. EXEMPLE SIMPLE import akka.http.scaladsl.Http import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport._ import akka.http.scaladsl.server.Directives._ import akka.stream.ActorMaterializer object Main extends App { implicit val system = ActorSystem("my-system") implicit val materializer = ActorMaterializer() implicit val ec = system.dispatcher val route = path("hello") { get { complete { <h1>Say hello to akka-http</h1> } } } val bindingFuture = Http().bindAndHandle(route, "localhost", 8080) println(s"Server online at http://localhost:8080/nPress RETURN to stop...") Console.readLine() // for the future transformations bindingFuture .flatMap(_.unbind()) // trigger unbinding from the port .onComplete(_ ⇒ system.shutdown()) // and shutdown when done }
  • 17. MARSHALLING/UNMARSHALLING Comment passer d'un flux HTTP à Scala et inversement ?
  • 19. MARSHALLING Résolution implicite Si le type ToEntityMarshaller[T] est défini, il est utilisé
  • 22. LOW-LEVEL import akka.http.scaladsl.Http import akka.http.scaladsl.model.HttpMethods._ import akka.http.scaladsl.model._ import akka.stream.ActorMaterializer implicit val system = ActorSystem() implicit val materializer = ActorMaterializer() val requestHandler: HttpRequest => HttpResponse = { case HttpRequest(GET, Uri.Path("/"), _, _, _) => HttpResponse(entity = HttpEntity(ContentTypes.`text/html(UTF-8)` , "Hello world!")) case HttpRequest(GET, Uri.Path("/ping"), _, _, _) => HttpResponse(entity = "PONG!") case HttpRequest(GET, Uri.Path("/crash"), _, _, _) => sys.error("BOOM!") case _: HttpRequest => HttpResponse(404, entity = "Unknown resource!") } Http().bindAndHandleSync(requestHandler, "localhost", 8080)
  • 23. HIGH-LEVEL import akka.http.scaladsl.Http import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport._ import akka.http.scaladsl.server.Directives._ import akka.stream.ActorMaterializer implicit val system = ActorSystem() implicit val materializer = ActorMaterializer() val route = get { pathSingleSlash { complete { <html> <body>Hello world!</body> </html> } } ~ path("ping") { complete("PONG!") } ~ path("crash") { sys.error("BOOM!") } }
  • 24. // `route` will be implicitly converted to `Flow` using `RouteResult .route2HandlerFlow` Http().bindAndHandle(route, "localhost", 8080)
  • 26. DIRECTIVES Intercepte la requête Filtrage de la requête Transformation de la requête ou réponse Extraire des informations
  • 27. EXEMPLE val route = path("order" / IntNumber) { id => (get | put) { extractMethod { m => complete(s"Received ${m.name} request for order $id") } } }
  • 28. EXEMPLE 2 val orderGetOrPutWithMethod = path("order" / IntNumber) & (get | put) & extractMethod val route = orderGetOrPutWithMethod { (id, m) => complete(s"Received ${m.name} request for order $id") }
  • 29. et PATHMATCHER val matcher: PathMatcher1[Option[Int]] = "foo" / "bar" / "X" ~ IntNumber.? / ("edit" | "create") Intercepte les chemins suivants : foo/bar/X42/edit foo/bar/X/create
  • 30. EXTRACTION CASE CLASS case class Color(red: Int, green: Int, blue: Int) val route = path("color") { parameters('red.as[Int], 'green.as[Int], 'blue.as[Int]).as(Color) { color => // utiliser color } }
  • 31. VALIDATION CASE CLASS case class Color(name: String, red: Int, green: Int, blue: Int) { require(!name.isEmpty, "color name must not be empty") require(0 <= red && red <= 255, "red color component must be betwe en 0 and 255") require(0 <= green && green <= 255, "green color component must be between 0 and 255") require(0 <= blue && blue <= 255, "blue color component must be be tween 0 and 255") } ValidationRejection si require ne passe pas Par défaut : 400 Bad Request
  • 32. TESTS
  • 33. Pour la route suivante val smallRoute = get { pathSingleSlash { complete { "Hello World !" } } ~ path("ping") { complete("PONG !") } } Test "Hello World ! non renvoyé sur /" in { Get() ~> smallRoute ~> check { status === StatusCodes.OK responseAs[String] shouldEqual "Hello World !" } }
  • 34. Pour la même route ... val smallRoute = get { pathSingleSlash { complete { "Hello World !" } } ~ path("ping") { complete("PONG !") } } Test "GET sur chemin inconnu non pris en compte" in { Get("/pouet") ~> smallRoute ~> check { handled shouldBe false } }
  • 35. VARIABLES UTILISABLES DANS LES TESTS entityAs handled header response status entre autres ...
  • 36. CLIENT val responseFuture: Future[HttpResponse] = Http().singleRequest(HttpRequest(uri = "http://akka.io"))
  • 38. MERCI POUR VOTRE ÉCOUTE Cette présentation : @thebignet thebignet thebignet talk-akka-http