SlideShare ist ein Scribd-Unternehmen logo
1 von 12
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Ähnlich wie 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
 

Ähnlich wie 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]
 

Mehr von Knoldus Inc.

Mehr von 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
 

Kürzlich hochgeladen

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Kürzlich hochgeladen (20)

How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
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
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
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...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 

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