SlideShare una empresa de Scribd logo
1 de 17
Sandeep
Trainee Software Consultant
Knoldus Software LLP
Sandeep
Trainee Software Consultant
Knoldus Software LLP
Topics CoveredTopics Covered
What is spray
Why we use spray
Spray application architecture
Spray-can HTTP server
Spray-routing
Demo
What is spray
Why we use spray
Spray application architecture
Spray-can HTTP server
Spray-routing
Demo
What is SprayWhat is Spray
spray is an open-source toolkit for building REST/HTTP-based integration
layers on top of Scala and Akka.
Principles of spray :-
● Fully asynchronous, non-blocking
● Actor- and Future-based
● High-performance
● Lightweight
● Modular
● Testable
Why we use sprayWhy we use spray
● To make RESTful web services
● REST should be used if it is very important for you to minimize the coupling
between client and server components in a distributed application.
● This may be the case if your server is going to be used by many different
clients that you do not have control over.
● Simply make a controller layer of MVC architecture
Spray-can Http serverSpray-can Http server
The spray-can HttpServer is scoped with a clear focus on the essential
functionality of an HTTP/1.1 server:
●
Connection management
● Message parsing and header separation
● Timeout management (for requests and connections)
● Response ordering (for transparent pipelining support)
The spray-can HTTP server is implemented by two types of Akka actors,
which sit on top of Akka IO. When you tell spray-can to start a new server
instance on a given port an HttpListener actor is started, which accepts
incoming connections and for each one spawns a new
HttpServerConnection actor, which then manages the connection for the
rest of its lifetime
Starting spray-can Http serverStarting spray-can Http server
// we need an ActorSystem to host our application in
implicit val system = ActorSystem("spray-api-service")
// create and start our service actor
val service = system.actorOf(Props[MyServiceActor], "spray-service")
// start a new HTTP server on port 8080 with our service actor as the handler
IO(Http) ! Http.Bind(service, interface = "localhost", port = 8080)
}
A spray-can HTTP server is started by sending an Http.Bind command to the
Http extension:
Spray-routing
The spray-routing module provides a high-level, very flexible routing DSL for elegantly defining
RESTful web services. Normally you would use it either on top of a spray-can HTTP Server.
Val routes = path("index") {
get {
respondWithMediaType(`text/html`) {
complete {
HttpResponse(OK, "Hello Sandeep ")
}
}
}
}
Directives
Directives are small building blocks of which you can construct arbitrarily
complex route structures. Here is a simple example of a route built from
directives:
A directive does one or more of the following:
● Transform the incoming RequestContext before passing it on to its inner Route
● Filter the RequestContext according to some logic, i.e. only pass on certain
requests and reject all others
● Extract values from the RequestContext and make them available to its inner
Route as “extractions”
● Complete the request
Composing directives
val route: Route =
path("order" / IntNumber) { id =>
get {
complete {
"Received GET request for order " + id
}
} ~
put {
complete {
"Received PUT request for order " + id
}
}
}
you can also use the | operator on directives
Get and put directives are chained together with the ~ operator to form a
higher-level route that serves as the inner Route of the path directive
Parameters
● .? (optional)
● ? "red" (default value)
● ! "blue" (color should be blue)
● .as[Int] (deserialize as a Int)
Query parameters can be either extracted as a String or can be converted
to another type. The parameter name can be supplied either as a String or
as a Symbol. Parameter extraction can be modified to mark a query
parameter as required or optional or to filter requests where a parameter
has a certain value
Get request parameters extract
val route =
parameters('color, 'backgroundColor) { (color, backgroundColor) =>
complete(s"The color is '$color' and the background is '$backgroundColor'")
}
Deserialize the parameters
val route =
parameters('color, 'count.as[Int]) { (color, count) =>
complete(s"The color is '$color' and you have $count of it.")
}
Marshalling
“Marshalling” is the process of converting a higher-level (object) structure
into some kind of lower-level representation, often a “wire format”. Other
popular names for it are “Serialization” or “Pickling”.
In spray “Marshalling” means the conversion of an object of type T into an
HttpEntity
spray-httpx comes with pre-defined Marshallers for the following types:
● Array[Byte]
● Array[Char]
● String
● Option[T]
● Either[A, B]
● Try[T]
● Future[T]
Unmarshalls
Entity Directive
The entity directive works in conjuction with as and spray.httpx.unmarshalling
to convert some serialized “wire format” value into a higher-level object
structure
val route = post {
entity(as[Person]) { person =>
complete(s"Person: ${person.name} - favorite number: $
{person.favoriteNumber}")
}
}
Spray test-kit
For services built with spray-routing spray provides a dedicated test DSL that
makes actor-less testing of route logic easy and convenient. This “route test DSL”
is made available with the spray-testkit module.
"return a 'PONG!' response for GET requests to /ping" in {
Get("/ping") ~> smallRoute ~> check {
responseAs[String] === "PONG!"
}
}
DEMO
Thank you

Más contenido relacionado

La actualidad más candente

Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsGuy Nir
 
Asp.Net Ajax Component Development
Asp.Net Ajax Component DevelopmentAsp.Net Ajax Component Development
Asp.Net Ajax Component DevelopmentChui-Wen Chiu
 
ASP.NET MVC 4 Request Pipeline Internals
ASP.NET MVC 4 Request Pipeline InternalsASP.NET MVC 4 Request Pipeline Internals
ASP.NET MVC 4 Request Pipeline InternalsLukasz Lysik
 
Flask & Flask-restx
Flask & Flask-restxFlask & Flask-restx
Flask & Flask-restxammaraslam18
 
Esri Dev Summit 2009 Rest and Mvc Final
Esri Dev Summit 2009 Rest and Mvc FinalEsri Dev Summit 2009 Rest and Mvc Final
Esri Dev Summit 2009 Rest and Mvc Finalguestcd4688
 
using Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API'susing Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API'sAntônio Roberto Silva
 
PostgREST Design Philosophy
PostgREST Design PhilosophyPostgREST Design Philosophy
PostgREST Design Philosophybegriffs
 
DataFX 8 (JavaOne 2014)
DataFX 8 (JavaOne 2014)DataFX 8 (JavaOne 2014)
DataFX 8 (JavaOne 2014)Hendrik Ebbers
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Tuna Tore
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods pptkamal kotecha
 
Front end development with Angular JS
Front end development with Angular JSFront end development with Angular JS
Front end development with Angular JSBipin
 

La actualidad más candente (20)

Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topics
 
Asp.Net Ajax Component Development
Asp.Net Ajax Component DevelopmentAsp.Net Ajax Component Development
Asp.Net Ajax Component Development
 
ASP.NET MVC 4 Request Pipeline Internals
ASP.NET MVC 4 Request Pipeline InternalsASP.NET MVC 4 Request Pipeline Internals
ASP.NET MVC 4 Request Pipeline Internals
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Spring Mvc Rest
Spring Mvc RestSpring Mvc Rest
Spring Mvc Rest
 
Angular 2
Angular 2Angular 2
Angular 2
 
Flask & Flask-restx
Flask & Flask-restxFlask & Flask-restx
Flask & Flask-restx
 
Esri Dev Summit 2009 Rest and Mvc Final
Esri Dev Summit 2009 Rest and Mvc FinalEsri Dev Summit 2009 Rest and Mvc Final
Esri Dev Summit 2009 Rest and Mvc Final
 
using Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API'susing Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API's
 
PostgREST Design Philosophy
PostgREST Design PhilosophyPostgREST Design Philosophy
PostgREST Design Philosophy
 
DataFX 8 (JavaOne 2014)
DataFX 8 (JavaOne 2014)DataFX 8 (JavaOne 2014)
DataFX 8 (JavaOne 2014)
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
Asp.Net MVC Intro
Asp.Net MVC IntroAsp.Net MVC Intro
Asp.Net MVC Intro
 
Refreshing mule cache using oracle database change notification
Refreshing mule cache using oracle database change notificationRefreshing mule cache using oracle database change notification
Refreshing mule cache using oracle database change notification
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
 
Jdbc api
Jdbc apiJdbc api
Jdbc api
 
Front end development with Angular JS
Front end development with Angular JSFront end development with Angular JS
Front end development with Angular JS
 
Slim Framework
Slim FrameworkSlim Framework
Slim Framework
 

Similar a Spray - Build RESTfull services in scala

Webservices in SalesForce (part 1)
Webservices in SalesForce (part 1)Webservices in SalesForce (part 1)
Webservices in SalesForce (part 1)Mindfire Solutions
 
SAP FIORI COEP Pune - pavan golesar (ppt)
SAP FIORI COEP Pune - pavan golesar (ppt)SAP FIORI COEP Pune - pavan golesar (ppt)
SAP FIORI COEP Pune - pavan golesar (ppt)Pavan Golesar
 
AK 3 web services using apache axis
AK 3   web services using apache axisAK 3   web services using apache axis
AK 3 web services using apache axisgauravashq
 
Create Home Directories on Storage Using WFA and ServiceNow integration
Create Home Directories on Storage Using WFA and ServiceNow integrationCreate Home Directories on Storage Using WFA and ServiceNow integration
Create Home Directories on Storage Using WFA and ServiceNow integrationRutul Shah
 
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...Dilouar Hossain
 
All About Microservices and OpenSource Microservice Frameworks
All About Microservices and OpenSource Microservice FrameworksAll About Microservices and OpenSource Microservice Frameworks
All About Microservices and OpenSource Microservice FrameworksMohammad Asif Siddiqui
 
MuleSoft London Community February 2020 - MuleSoft and OData
MuleSoft London Community February 2020 - MuleSoft and ODataMuleSoft London Community February 2020 - MuleSoft and OData
MuleSoft London Community February 2020 - MuleSoft and ODataPace Integration
 
Building REST API using Akka HTTP with Scala
Building REST API using Akka HTTP with ScalaBuilding REST API using Akka HTTP with Scala
Building REST API using Akka HTTP with ScalaKnoldus Inc.
 
2014 Taverna tutorial REST services
2014 Taverna tutorial REST services2014 Taverna tutorial REST services
2014 Taverna tutorial REST servicesmyGrid team
 
Design Summit - RESTful API Overview - John Hardy
Design Summit - RESTful API Overview - John HardyDesign Summit - RESTful API Overview - John Hardy
Design Summit - RESTful API Overview - John HardyManageIQ
 
Code igniter - A brief introduction
Code igniter - A brief introductionCode igniter - A brief introduction
Code igniter - A brief introductionCommit University
 
Overview of MVC Framework - by software outsourcing company india
Overview of MVC Framework - by software outsourcing company indiaOverview of MVC Framework - by software outsourcing company india
Overview of MVC Framework - by software outsourcing company indiaJignesh Aakoliya
 
Rest service in mule
Rest service in mule Rest service in mule
Rest service in mule Harish43
 
Intro to web services
Intro to web servicesIntro to web services
Intro to web servicesNeil Ghosh
 

Similar a Spray - Build RESTfull services in scala (20)

Webservices in SalesForce (part 1)
Webservices in SalesForce (part 1)Webservices in SalesForce (part 1)
Webservices in SalesForce (part 1)
 
SAP FIORI COEP Pune - pavan golesar (ppt)
SAP FIORI COEP Pune - pavan golesar (ppt)SAP FIORI COEP Pune - pavan golesar (ppt)
SAP FIORI COEP Pune - pavan golesar (ppt)
 
AK 3 web services using apache axis
AK 3   web services using apache axisAK 3   web services using apache axis
AK 3 web services using apache axis
 
Create Home Directories on Storage Using WFA and ServiceNow integration
Create Home Directories on Storage Using WFA and ServiceNow integrationCreate Home Directories on Storage Using WFA and ServiceNow integration
Create Home Directories on Storage Using WFA and ServiceNow integration
 
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
 
All About Microservices and OpenSource Microservice Frameworks
All About Microservices and OpenSource Microservice FrameworksAll About Microservices and OpenSource Microservice Frameworks
All About Microservices and OpenSource Microservice Frameworks
 
MuleSoft London Community February 2020 - MuleSoft and OData
MuleSoft London Community February 2020 - MuleSoft and ODataMuleSoft London Community February 2020 - MuleSoft and OData
MuleSoft London Community February 2020 - MuleSoft and OData
 
Rest web services
Rest web servicesRest web services
Rest web services
 
Building REST API using Akka HTTP with Scala
Building REST API using Akka HTTP with ScalaBuilding REST API using Akka HTTP with Scala
Building REST API using Akka HTTP with Scala
 
2014 Taverna tutorial REST services
2014 Taverna tutorial REST services2014 Taverna tutorial REST services
2014 Taverna tutorial REST services
 
Design Summit - RESTful API Overview - John Hardy
Design Summit - RESTful API Overview - John HardyDesign Summit - RESTful API Overview - John Hardy
Design Summit - RESTful API Overview - John Hardy
 
Code igniter - A brief introduction
Code igniter - A brief introductionCode igniter - A brief introduction
Code igniter - A brief introduction
 
Overview of MVC Framework - by software outsourcing company india
Overview of MVC Framework - by software outsourcing company indiaOverview of MVC Framework - by software outsourcing company india
Overview of MVC Framework - by software outsourcing company india
 
Rest service in mule
Rest service in mule Rest service in mule
Rest service in mule
 
sveltekit-en.pdf
sveltekit-en.pdfsveltekit-en.pdf
sveltekit-en.pdf
 
Express node js
Express node jsExpress node js
Express node js
 
Rest Service In Mule
Rest Service In Mule Rest Service In Mule
Rest Service In Mule
 
Mvc
MvcMvc
Mvc
 
Intro to web services
Intro to web servicesIntro to web services
Intro to web services
 
Switch to Backend 2023
Switch to Backend 2023Switch to Backend 2023
Switch to Backend 2023
 

Último

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 WorkerThousandEyes
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
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...apidays
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
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 CVKhem
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
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 DiscoveryTrustArc
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
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 2024The Digital Insurer
 

Último (20)

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
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
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 future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
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
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
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
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
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
 

Spray - Build RESTfull services in scala

  • 1. Sandeep Trainee Software Consultant Knoldus Software LLP Sandeep Trainee Software Consultant Knoldus Software LLP
  • 2. Topics CoveredTopics Covered What is spray Why we use spray Spray application architecture Spray-can HTTP server Spray-routing Demo What is spray Why we use spray Spray application architecture Spray-can HTTP server Spray-routing Demo
  • 3. What is SprayWhat is Spray spray is an open-source toolkit for building REST/HTTP-based integration layers on top of Scala and Akka. Principles of spray :- ● Fully asynchronous, non-blocking ● Actor- and Future-based ● High-performance ● Lightweight ● Modular ● Testable
  • 4. Why we use sprayWhy we use spray ● To make RESTful web services ● REST should be used if it is very important for you to minimize the coupling between client and server components in a distributed application. ● This may be the case if your server is going to be used by many different clients that you do not have control over. ● Simply make a controller layer of MVC architecture
  • 5.
  • 6. Spray-can Http serverSpray-can Http server The spray-can HttpServer is scoped with a clear focus on the essential functionality of an HTTP/1.1 server: ● Connection management ● Message parsing and header separation ● Timeout management (for requests and connections) ● Response ordering (for transparent pipelining support) The spray-can HTTP server is implemented by two types of Akka actors, which sit on top of Akka IO. When you tell spray-can to start a new server instance on a given port an HttpListener actor is started, which accepts incoming connections and for each one spawns a new HttpServerConnection actor, which then manages the connection for the rest of its lifetime
  • 7. Starting spray-can Http serverStarting spray-can Http server // we need an ActorSystem to host our application in implicit val system = ActorSystem("spray-api-service") // create and start our service actor val service = system.actorOf(Props[MyServiceActor], "spray-service") // start a new HTTP server on port 8080 with our service actor as the handler IO(Http) ! Http.Bind(service, interface = "localhost", port = 8080) } A spray-can HTTP server is started by sending an Http.Bind command to the Http extension:
  • 8. Spray-routing The spray-routing module provides a high-level, very flexible routing DSL for elegantly defining RESTful web services. Normally you would use it either on top of a spray-can HTTP Server. Val routes = path("index") { get { respondWithMediaType(`text/html`) { complete { HttpResponse(OK, "Hello Sandeep ") } } } }
  • 9. Directives Directives are small building blocks of which you can construct arbitrarily complex route structures. Here is a simple example of a route built from directives: A directive does one or more of the following: ● Transform the incoming RequestContext before passing it on to its inner Route ● Filter the RequestContext according to some logic, i.e. only pass on certain requests and reject all others ● Extract values from the RequestContext and make them available to its inner Route as “extractions” ● Complete the request
  • 10. Composing directives val route: Route = path("order" / IntNumber) { id => get { complete { "Received GET request for order " + id } } ~ put { complete { "Received PUT request for order " + id } } } you can also use the | operator on directives Get and put directives are chained together with the ~ operator to form a higher-level route that serves as the inner Route of the path directive
  • 11. Parameters ● .? (optional) ● ? "red" (default value) ● ! "blue" (color should be blue) ● .as[Int] (deserialize as a Int) Query parameters can be either extracted as a String or can be converted to another type. The parameter name can be supplied either as a String or as a Symbol. Parameter extraction can be modified to mark a query parameter as required or optional or to filter requests where a parameter has a certain value
  • 12. Get request parameters extract val route = parameters('color, 'backgroundColor) { (color, backgroundColor) => complete(s"The color is '$color' and the background is '$backgroundColor'") } Deserialize the parameters val route = parameters('color, 'count.as[Int]) { (color, count) => complete(s"The color is '$color' and you have $count of it.") }
  • 13. Marshalling “Marshalling” is the process of converting a higher-level (object) structure into some kind of lower-level representation, often a “wire format”. Other popular names for it are “Serialization” or “Pickling”. In spray “Marshalling” means the conversion of an object of type T into an HttpEntity spray-httpx comes with pre-defined Marshallers for the following types: ● Array[Byte] ● Array[Char] ● String ● Option[T] ● Either[A, B] ● Try[T] ● Future[T]
  • 14. Unmarshalls Entity Directive The entity directive works in conjuction with as and spray.httpx.unmarshalling to convert some serialized “wire format” value into a higher-level object structure val route = post { entity(as[Person]) { person => complete(s"Person: ${person.name} - favorite number: $ {person.favoriteNumber}") } }
  • 15. Spray test-kit For services built with spray-routing spray provides a dedicated test DSL that makes actor-less testing of route logic easy and convenient. This “route test DSL” is made available with the spray-testkit module. "return a 'PONG!' response for GET requests to /ping" in { Get("/ping") ~> smallRoute ~> check { responseAs[String] === "PONG!" } }
  • 16. DEMO