Scala hello world web api with http4s
Build.sbt
scalaVersion := "2.13.6" // Also supports 2.12.x
val http4sVersion = "0.23.1"
// Only necessary for SNAPSHOT releases
resolvers += Resolver.sonatypeRepo("snapshots")
libraryDependencies ++= Seq(
"org.http4s" %% "http4s-dsl" % http4sVersion,
"org.http4s" %% "http4s-blaze-server" % http4sVersion,
"org.http4s" %% "http4s-blaze-client" % http4sVersion
)
Server.scala
package bkr.joker.webapi
import cats.effect._
import org.http4s.blaze.server._
import scala.concurrent.ExecutionContext.global
// import cats.effect._
import org.http4s.HttpRoutes
import org.http4s.dsl.io._
import org.http4s.implicits._
object Server extends IOApp {
def plot(name: String, lastname: String): String = {
s"All work and no play makes $name $lastname a dull boy."
}
val routes = HttpRoutes.of[IO] {
case GET -> Root / "health" =>
Ok("I'm here")
case GET -> Root / "plot" / name / lastname =>
Ok(plot(name, lastname))
}.orNotFound
def run(args: List[String]): IO[ExitCode] =
BlazeServerBuilder[IO](global)
.bindHttp(8080, "localhost")
.withHttpApp(routes)
.serve
.compile
.drain
.as(ExitCode.Success)
}