Http4s and doobie
http4s is a type safe, functional, HTTP streaming library for Scala. It built based on
cats library. We can build pure functional REST applications with full control of side-effects with
doobie is a pure functional JDBC layer for scala. It also built with with cats library.
On my previous post I have discussed about
cats-effects. In this post I’m gonna discuss about building REST application with
cats-effects. All the source codes which relates to this post available on gitlab. Please clone the repo and continue the post.
IntelliJ Idea as my IDE to work with Scala applications. I need to create
sbt project and add the
build.sbt dependency file with
doobie and other dependencies. Following is the
build.sbt dependency file.
I’m using cats-effects
IO monads to build this application. To load the configurations(
server config) with
IO monads I have used
circe-config library. Following is the way to parse configurations into cats-effects
To connect to the database, I need to create an instance of a
doobie transactor. In here I’m using
HikariTransactor which built based on
HikariCP database connection pooling library. Following are the functions to build
HikariTransactor and bootstrap the database. All of these functions built with cats-effects IO monads.
In this application I’m dealing with a model,
Account. Account models are saving on
mysql database table,
mystiko.accounts. Following is the Account model structure and database table structure.
doobie queries are written directly in
SQL. Following are the
doobie queries that I have used to perform the CURD operations with the data on
To execute above queries I need to create data layer functions. I have created DB repository(
AccountRepo) with following
Next thing is create HTTP interface(
HttpRoutes) to interact with
AccountRepo functions. Following is the way to define these endpoints in terms of
To make this REST API live I need to create a server and bind the these routes to it(in
http4s routes do not handle any requests until we explicitly associate them with running server). Following is the way to bind routes to
http4s native server
blaze. I have used cats-effects
IO monads in here as well.
mysql as the database backend. In order to test this application I need to run the
mysql and create a database on it. Following is the way to do that with with
When we run this application it will starts four REST API end points. I can test these end points with following