SlideShare una empresa de Scribd logo
1 de 12
Descargar para leer sin conexión
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

Más contenido relacionado

Similar a 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
 

Similar a 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]
 

Más de Knoldus Inc.

Más 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
 

Último

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
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
+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@
 

Último (20)

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
 
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
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
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...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
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
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
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 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
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
 
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
 
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...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
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...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
+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...
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 

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