SlideShare une entreprise Scribd logo
1  sur  12
Télécharger pour lire hors ligne
Presented By: Swantika Gupta
Dig Deeper With
http4s
Lack of etiquette and manners is a huge turn off.
KnolX Etiquettes
Punctuality
Join the session 5 minutes prior to
the session start time. We start on
time and conclude on time!
Feedback
Make sure to submit a constructive
feedback for all sessions as it is
very helpful for the presenter.
Silent Mode
Keep your mobile devices in silent
mode, feel free to move out of
session in case you need to attend
an urgent call.
Avoid Disturbance
Avoid unwanted chit chat during
the session.
Our Agenda
Recap of http4s
Introducing Middleware in http4s
Demo with Basic http4s Routes
Demo with http4s Routes + middleware
Basics of http4s
type HttpRoutes = Kleisli [ OptionT [ F, * ], Request, Response ]
http4s - Recap
● Lightweight Library
● Typeful
● Purely Functional
● Based on Cats and fs2-streaming
● Streaming
● Performant
Heart of http4s
http4s DSL
object LocalDateVar {
def unapply(str: String): Option[LocalDate] = {
if (!str.isEmpty)
Try(LocalDate.parse(str)).toOption
else
None
}
}
case GET -> Root / "weather" / "temperature" / LocalDateVar(localDate) =>
Ok(getTemperatureForecast(localDate)
.map(s"The temperature on $localDate will be: " + _))
http4s - Recap
val route: HttpRoutes[IO] = HttpRoutes.of[IO] {
case GET -> Root / "length" / str => Ok(str.length.toString)
case GET -> Root / "hello" / name => Ok(s"""Hello, ${name}!""")
}
Handling Path Parameters
QueryParamDecoderMatcher
object OptionalYearQueryParamMatcher
extends OptionalQueryParamDecoderMatcher[Year]("year")
val routes = HttpRoutes.of[IO] {
case GET -> Root / "temperature" :?
OptionalYearQueryParamMatcher(maybeYear) =>
maybeYear match {
case None => Ok(getAverageTemperatureForCurrentYear)
case Some(year) => Ok(getAverageTemperatureForYear(year))
}
}
Ex: /temperature or /temperature?year=2005
http4s - Recap
implicit val yearQueryParamDecoder: QueryParamDecoder[Year] =
QueryParamDecoder[Int].map(Year.of)
object YearQueryParamMatcher
extends QueryParamDecoderMatcher[Year]("year")
case GET -> Root / "weather" / "temperature"
:? YearQueryParamMatcher(year) =>
Ok(getAverageTemperatureForYear(year)
.map(s"Average temperature for $country in $year was: " + _))
Ex: /weather/temperature?year=2005
OptionalQueryParamDecoderMatcher
ValidatingQueryParamDecoderMatcher
object LongParamMatcher
extends OptionalValidatingQueryParamDecoderMatcher[Long]("long")
case GET -> Root / "number" :? LongParamMatcher(maybeNumber) =>
maybeNumber match {
case Some(n) =>
n.fold(
parseFailures => BadRequest("unable to parse argument 'long'"),
year => Ok(n.toString)
)
case None => BadRequest("missing number")
}
Ex: /number?long=13
http4s - Recap
implicit val yearQueryParamDecoder = QueryParamDecoder[Int]
.emap(i => Try(Year.of(i))
.toEither
.leftMap(t => ParseFailure(t.getMessage, t.getMessage)))
object YearQueryParamMatcher
extends ValidatingQueryParamDecoderMatcher[Year]("year")
case GET -> Root / "temperature" :?
YearQueryParamMatcher(yearValidated) =>
yearValidated.fold(
parseFailures => BadRequest("unable to parse argument year"),
year => Ok(getAverageTemperatureForYear(year))
)
Ex: /temperature?year=2005
OptionalValidatingQueryParamDecoderMatcher
http4s Server
def healthCheck(client: Client[IO]): IO[String] =
client.expect[String](s"$baseUri/healthcheck")
EmberClientBuilder.default[IO].build
.use { client =>
healthCheck(client).unsafeRunSync()
}
http4s - Recap
EmberServerBuilder
.default[IO]
.withHost(Host.fromString(host).get)
.withPort(Port.fromInt(port).get)
.withHttpApp(new HttpService().combinedRoutes)
.build
.use(_ => IO.never)
.as(ExitCode.Success)
http4s Client
Demo
with
http4s Routes
● Abstraction around a service
● Manipulate the request sent to a service and/or response
returned by the service
● Function that takes one service and returns another service
● Ex: def addHeaders(
service: HttpRoutes[IO],
header: Header.ToRaw
): HttpRoutes[IO]
addHeaders(
userServiceAPI,
"extra-added-header" -> "extra-header-value"
)
http4s - Middleware
http4s includes some middleware OOB in the codebase:
● Authentication
● CORS
● Response Compression
● Metrics
● Loggers
Demo
with
http4s Routes
and
Middleware
Thank You !
Get in touch with us:
Scala Studio, Knoldus

Contenu connexe

Similaire à Dig Deeper With http4s

Refactoring In Tdd The Missing Part
Refactoring In Tdd The Missing PartRefactoring In Tdd The Missing Part
Refactoring In Tdd The Missing Part
Gabriele Lana
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
Amit Thakkar
 

Similaire à Dig Deeper With http4s (20)

entwickler.de Go Day: Go Web Development 101
entwickler.de Go Day: Go Web Development 101entwickler.de Go Day: Go Web Development 101
entwickler.de Go Day: Go Web Development 101
 
The why and how of moving to php 5.4/5.5
The why and how of moving to php 5.4/5.5The why and how of moving to php 5.4/5.5
The why and how of moving to php 5.4/5.5
 
swift-nio のアーキテクチャーと RxHttpClient
swift-nio のアーキテクチャーと RxHttpClientswift-nio のアーキテクチャーと RxHttpClient
swift-nio のアーキテクチャーと RxHttpClient
 
Refactoring In Tdd The Missing Part
Refactoring In Tdd The Missing PartRefactoring In Tdd The Missing Part
Refactoring In Tdd The Missing Part
 
About Node.js
About Node.jsAbout Node.js
About Node.js
 
Continuous Application with FAIR Scheduler with Robert Xue
Continuous Application with FAIR Scheduler with Robert XueContinuous Application with FAIR Scheduler with Robert Xue
Continuous Application with FAIR Scheduler with Robert Xue
 
The why and how of moving to PHP 5.4/5.5
The why and how of moving to PHP 5.4/5.5The why and how of moving to PHP 5.4/5.5
The why and how of moving to PHP 5.4/5.5
 
WebTalk - Implementing Web Services with a dedicated Java daemon
WebTalk - Implementing Web Services with a dedicated Java daemonWebTalk - Implementing Web Services with a dedicated Java daemon
WebTalk - Implementing Web Services with a dedicated Java daemon
 
Beyond parallelize and collect - Spark Summit East 2016
Beyond parallelize and collect - Spark Summit East 2016Beyond parallelize and collect - Spark Summit East 2016
Beyond parallelize and collect - Spark Summit East 2016
 
Leveraging Hadoop in your PostgreSQL Environment
Leveraging Hadoop in your PostgreSQL EnvironmentLeveraging Hadoop in your PostgreSQL Environment
Leveraging Hadoop in your PostgreSQL Environment
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...
 
Php extensions
Php extensionsPhp extensions
Php extensions
 
SwampDragon presentation: The Copenhagen Django Meetup Group
SwampDragon presentation: The Copenhagen Django Meetup GroupSwampDragon presentation: The Copenhagen Django Meetup Group
SwampDragon presentation: The Copenhagen Django Meetup Group
 
700 Tons of Code Later
700 Tons of Code Later700 Tons of Code Later
700 Tons of Code Later
 
Setting Up a TIG Stack for Your Testing
Setting Up a TIG Stack for Your TestingSetting Up a TIG Stack for Your Testing
Setting Up a TIG Stack for Your Testing
 
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
 
storm-170531123446.pptx
storm-170531123446.pptxstorm-170531123446.pptx
storm-170531123446.pptx
 
LCDS - State Presentation
LCDS - State PresentationLCDS - State Presentation
LCDS - State Presentation
 
Netconf for Peering Automation by Tom Paseka [APRICOT 2015]
Netconf for Peering Automation by Tom Paseka [APRICOT 2015]Netconf for Peering Automation by Tom Paseka [APRICOT 2015]
Netconf for Peering Automation by Tom Paseka [APRICOT 2015]
 

Plus de Knoldus Inc.

Plus de Knoldus Inc. (20)

Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptx
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptx
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptx
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake Presentation
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics Presentation
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIs
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II Presentation
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRA
 

Dernier

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
panagenda
 
+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@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
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
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
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
 
+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...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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
 
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
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
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...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
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
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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
 

Dig Deeper With http4s

  • 1. Presented By: Swantika Gupta Dig Deeper With http4s
  • 2. Lack of etiquette and manners is a huge turn off. KnolX Etiquettes Punctuality Join the session 5 minutes prior to the session start time. We start on time and conclude on time! Feedback Make sure to submit a constructive feedback for all sessions as it is very helpful for the presenter. Silent Mode Keep your mobile devices in silent mode, feel free to move out of session in case you need to attend an urgent call. Avoid Disturbance Avoid unwanted chit chat during the session.
  • 3. Our Agenda Recap of http4s Introducing Middleware in http4s Demo with Basic http4s Routes Demo with http4s Routes + middleware
  • 4. Basics of http4s type HttpRoutes = Kleisli [ OptionT [ F, * ], Request, Response ] http4s - Recap ● Lightweight Library ● Typeful ● Purely Functional ● Based on Cats and fs2-streaming ● Streaming ● Performant Heart of http4s
  • 5. http4s DSL object LocalDateVar { def unapply(str: String): Option[LocalDate] = { if (!str.isEmpty) Try(LocalDate.parse(str)).toOption else None } } case GET -> Root / "weather" / "temperature" / LocalDateVar(localDate) => Ok(getTemperatureForecast(localDate) .map(s"The temperature on $localDate will be: " + _)) http4s - Recap val route: HttpRoutes[IO] = HttpRoutes.of[IO] { case GET -> Root / "length" / str => Ok(str.length.toString) case GET -> Root / "hello" / name => Ok(s"""Hello, ${name}!""") } Handling Path Parameters
  • 6. QueryParamDecoderMatcher object OptionalYearQueryParamMatcher extends OptionalQueryParamDecoderMatcher[Year]("year") val routes = HttpRoutes.of[IO] { case GET -> Root / "temperature" :? OptionalYearQueryParamMatcher(maybeYear) => maybeYear match { case None => Ok(getAverageTemperatureForCurrentYear) case Some(year) => Ok(getAverageTemperatureForYear(year)) } } Ex: /temperature or /temperature?year=2005 http4s - Recap implicit val yearQueryParamDecoder: QueryParamDecoder[Year] = QueryParamDecoder[Int].map(Year.of) object YearQueryParamMatcher extends QueryParamDecoderMatcher[Year]("year") case GET -> Root / "weather" / "temperature" :? YearQueryParamMatcher(year) => Ok(getAverageTemperatureForYear(year) .map(s"Average temperature for $country in $year was: " + _)) Ex: /weather/temperature?year=2005 OptionalQueryParamDecoderMatcher
  • 7. ValidatingQueryParamDecoderMatcher object LongParamMatcher extends OptionalValidatingQueryParamDecoderMatcher[Long]("long") case GET -> Root / "number" :? LongParamMatcher(maybeNumber) => maybeNumber match { case Some(n) => n.fold( parseFailures => BadRequest("unable to parse argument 'long'"), year => Ok(n.toString) ) case None => BadRequest("missing number") } Ex: /number?long=13 http4s - Recap implicit val yearQueryParamDecoder = QueryParamDecoder[Int] .emap(i => Try(Year.of(i)) .toEither .leftMap(t => ParseFailure(t.getMessage, t.getMessage))) object YearQueryParamMatcher extends ValidatingQueryParamDecoderMatcher[Year]("year") case GET -> Root / "temperature" :? YearQueryParamMatcher(yearValidated) => yearValidated.fold( parseFailures => BadRequest("unable to parse argument year"), year => Ok(getAverageTemperatureForYear(year)) ) Ex: /temperature?year=2005 OptionalValidatingQueryParamDecoderMatcher
  • 8. http4s Server def healthCheck(client: Client[IO]): IO[String] = client.expect[String](s"$baseUri/healthcheck") EmberClientBuilder.default[IO].build .use { client => healthCheck(client).unsafeRunSync() } http4s - Recap EmberServerBuilder .default[IO] .withHost(Host.fromString(host).get) .withPort(Port.fromInt(port).get) .withHttpApp(new HttpService().combinedRoutes) .build .use(_ => IO.never) .as(ExitCode.Success) http4s Client
  • 10. ● Abstraction around a service ● Manipulate the request sent to a service and/or response returned by the service ● Function that takes one service and returns another service ● Ex: def addHeaders( service: HttpRoutes[IO], header: Header.ToRaw ): HttpRoutes[IO] addHeaders( userServiceAPI, "extra-added-header" -> "extra-header-value" ) http4s - Middleware http4s includes some middleware OOB in the codebase: ● Authentication ● CORS ● Response Compression ● Metrics ● Loggers
  • 12. Thank You ! Get in touch with us: Scala Studio, Knoldus