Finch provides a combinator API over the Finagle HTTP services. An Endpoint[A]
, main
abstraction for which combinators are defined, represents an HTTP endpoint that takes a request and
returns a value of type A
.
The following example creates an HTTP server (powered by Finagle) that serves the only endpoint
POST /time
. This endpoint takes a Locale
instance represented as JSON in request body and
returns a current Time
for this locale.
build.sbt:
libraryDependencies ++= Seq(
"com.github.finagle" %% "finch-core" % "0.12.0",
"com.github.finagle" %% "finch-circe" % "0.12.0",
"io.circe" %% "circe-generic" % "0.7.0-M1"
)
Main.scala:
import com.twitter.finagle.Http
import com.twitter.util.Await
import io.finch._
import io.finch.circe._
import io.circe.generic.auto._
object Main extends App {
case class Locale(language: String, country: String)
case class Time(locale: Locale, time: String)
def currentTime(l: java.util.Locale): String =
java.util.Calendar.getInstance(l).getTime.toString
val time: Endpoint[Time] =
post("time" :: jsonBody[Locale]) { l: Locale =>
Ok(Time(l, currentTime(new java.util.Locale(l.language, l.country))))
}
Await.ready(Http.server.serve(":8081", time.toService))
}
@mandubian on Twitter:
I think there is clearly room for great improvements using pure FP in Scala for HTTP API & #Finch is clearly a good candidate.
I'm currently working on a project using Finch (with Circe to serialize my case classes to JSON without any boilerplate code -- in fact, besides the import statements, I don't have to do anything to transform my results to JSON) and am extremely impressed. There are still a few things in flux with Finch, but I'd recommend giving it a look.
@arnarthor on Gitter:
I am currently re-writing a NodeJS service in Finch and the code is so much cleaner and readable and about two thirds the amount of lines. Really love this.
- Functional Microservices with Finch and Circe by @davegurnell in Nov 16
- Typed Services Using Finch by @tomjadams in Apr 2016
- Finch: Your REST API as a Monad by @vkostyukov in Dec 2015
- On the history of Finch by @vkostyukov in Apr 2015
- Some possible features for Finch @travisbrown in Apr 2015