Exploring ZIO HTTP
Presenter Name: Niloy Choudhury
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.
1. What is ZIO HTTP
 Http servers in general
 Mechanisms offered by ZIO HTTP
 How to write ZIO HTTP server (syntax)
2. ZIO HTTP Routing
3. Handlers, Query Params and URL Path
4. Request Response Interception (Middleware)
5. Error Handling
6. Server configuration
• A powerful library for building robust and scalable HTTP
servers.
• ZIO Http offers a functional and type-safe approach to server
development.
• Promotes code that's easy to understand, maintain, and test.
Http servers in general
 Routing
o Http Methods
o Path Variable
o Query Param
o Parse Request
 Request Response Interception
o Logging
o Middleware
 Error Handling
 Server Configuration
• A powerful routing mechanism for defining how incoming
requests map to specific handlers.
• Routes are built using a DSL.
• Plain data, description of route.
• Not pattern matching or partial function.
Routes
 Routes
o Models a collection of Route s
final case class Routes[-Env, +Err](routes: Chunk[zio.http.Route[Env,
Err]])
 A Route consists of two parts: RoutePattern and Handler
Method.GET / "hello" -> Handler.text("hello")
sealed trait Route[-Env, +Err]
o RoutePattern define how URLs map to handlers.
o Patterns can include literal strings, wildcards for any path segment, and path parameters.
o The Handler produces response to the matching request.
Handler
 A Handler is responsible for processing the matched incoming HTTP requests and generating
appropriate response.
sealed trait Handler[-R, +Err, -In, +Out]
type RequestHandler[-R, +Err] = Handler[R, Err, Request, Response]
o Function that takes a Request, including headers, body, and parameters.
o Generates a Response object.
o Response including status code, headers, and an optional body.
 Creating Handler
o Using companion object
Method.GET / "hello" -> Handler.text("hello !")
Method.GET / "forbidden" -> Handler.error(Status.Forbidden)
o Using smart constructor handler
Method.GET / Root -> handler(Response.text("Greetings at your service"))
Request
 ZIO HTTP Request represents a Http
request object
 Accessing incoming Request
o Method.POST / "echo" -> handler { req:
Request =>
req.body.asString.map(Response.text(_))
}.sandbox
 Query Params (Not part of the route)
o Method.GET / "search" -> handler { (req:
Request) =>
val queries: Option[String] =
req.queryParam("q")
...
 final case class Request(
version: Version = Version.Default,
method: Method = Method.ANY,
url: URL = URL.empty,
headers: Headers = Headers.empty,
body: Body = Body.empty,
remoteAddress: Option[InetAddress] =
None,
remoteCertificate: Option[Certificate] =
None,
) extends HeaderOps[Request]
Request object
Request Response Interception (Middleware)
 Intercept HTTP requests and responses before they reach the handler.
 Implement cross-cutting concerns like logging, validation.
 Accepts a Routes and produces a new Routes.
 Middleware can be chained together to form a processing pipeline for requests and responses.
 trait Middleware[-UpperEnv] { self =>
def apply[Env1 <: UpperEnv, Err](app: Routes[Env1, Err]): Routes[Env1, Err]
...
 private val logWithUserAgent: Middleware[Any] =
Middleware.logAnnotateHeaders(Header.UserAgent)
 routes @@ requestLogging @@ logWithUserAgent
Server Configuration
 ZIO HTTP server provides methods to install HTTP applications into the server.
 Offers a comprehensive Config class for control over server behavior, helps to configure
o SSL/TLS
o address binding
o request decompression
o response compression
 Serve routes using the Server.serve method
o Server.serve(routes).provide(Server.default)
 Customizing config
o Server.serve(ZIORoutes.routes)
.provide(ZLayer.succeed(Server.Config.default.port(8081)),
Server.live
)
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development

ZIO Http A Functional Approach to Scalable and Type-Safe Web Development

  • 1.
    Exploring ZIO HTTP PresenterName: Niloy Choudhury
  • 2.
    Lack of etiquetteand 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.
    1. What isZIO HTTP  Http servers in general  Mechanisms offered by ZIO HTTP  How to write ZIO HTTP server (syntax) 2. ZIO HTTP Routing 3. Handlers, Query Params and URL Path 4. Request Response Interception (Middleware) 5. Error Handling 6. Server configuration
  • 4.
    • A powerfullibrary for building robust and scalable HTTP servers. • ZIO Http offers a functional and type-safe approach to server development. • Promotes code that's easy to understand, maintain, and test.
  • 5.
    Http servers ingeneral  Routing o Http Methods o Path Variable o Query Param o Parse Request  Request Response Interception o Logging o Middleware  Error Handling  Server Configuration
  • 6.
    • A powerfulrouting mechanism for defining how incoming requests map to specific handlers. • Routes are built using a DSL. • Plain data, description of route. • Not pattern matching or partial function.
  • 7.
    Routes  Routes o Modelsa collection of Route s final case class Routes[-Env, +Err](routes: Chunk[zio.http.Route[Env, Err]])  A Route consists of two parts: RoutePattern and Handler Method.GET / "hello" -> Handler.text("hello") sealed trait Route[-Env, +Err] o RoutePattern define how URLs map to handlers. o Patterns can include literal strings, wildcards for any path segment, and path parameters. o The Handler produces response to the matching request.
  • 8.
    Handler  A Handleris responsible for processing the matched incoming HTTP requests and generating appropriate response. sealed trait Handler[-R, +Err, -In, +Out] type RequestHandler[-R, +Err] = Handler[R, Err, Request, Response] o Function that takes a Request, including headers, body, and parameters. o Generates a Response object. o Response including status code, headers, and an optional body.  Creating Handler o Using companion object Method.GET / "hello" -> Handler.text("hello !") Method.GET / "forbidden" -> Handler.error(Status.Forbidden) o Using smart constructor handler Method.GET / Root -> handler(Response.text("Greetings at your service"))
  • 9.
    Request  ZIO HTTPRequest represents a Http request object  Accessing incoming Request o Method.POST / "echo" -> handler { req: Request => req.body.asString.map(Response.text(_)) }.sandbox  Query Params (Not part of the route) o Method.GET / "search" -> handler { (req: Request) => val queries: Option[String] = req.queryParam("q") ...  final case class Request( version: Version = Version.Default, method: Method = Method.ANY, url: URL = URL.empty, headers: Headers = Headers.empty, body: Body = Body.empty, remoteAddress: Option[InetAddress] = None, remoteCertificate: Option[Certificate] = None, ) extends HeaderOps[Request] Request object
  • 10.
    Request Response Interception(Middleware)  Intercept HTTP requests and responses before they reach the handler.  Implement cross-cutting concerns like logging, validation.  Accepts a Routes and produces a new Routes.  Middleware can be chained together to form a processing pipeline for requests and responses.  trait Middleware[-UpperEnv] { self => def apply[Env1 <: UpperEnv, Err](app: Routes[Env1, Err]): Routes[Env1, Err] ...  private val logWithUserAgent: Middleware[Any] = Middleware.logAnnotateHeaders(Header.UserAgent)  routes @@ requestLogging @@ logWithUserAgent
  • 11.
    Server Configuration  ZIOHTTP server provides methods to install HTTP applications into the server.  Offers a comprehensive Config class for control over server behavior, helps to configure o SSL/TLS o address binding o request decompression o response compression  Serve routes using the Server.serve method o Server.serve(routes).provide(Server.default)  Customizing config o Server.serve(ZIORoutes.routes) .provide(ZLayer.succeed(Server.Config.default.port(8081)), Server.live )