This tutorial will walk you through creating your first http4s service and calling it with http4s’ client.

Create a new directory, with the following build.sbt in the root:

scalaVersion := "2.11.8" // Also supports 2.10.x and 2.12.x

val http4sVersion = "0.18.0-SNAPSHOT"

// 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

This tutorial is compiled as part of the build using tut. Each page is its own REPL session. If you copy and paste code samples starting from the top, you should be able to follow along in a REPL.

$ sbt console

Your first service

An HttpService[F] is a simple alias for Kleisli[F, Request, Response]. If that’s meaningful to you, great. If not, don’t panic: Kleisli is just a convenient wrapper around a Request => F[Response], and F is an effectful operation. We’ll teach you what you need to know as we go, or you can, uh, fork a task to read these introductions first:

Defining your service

Wherever you are in your studies, let’s create our first HttpService. Start by pasting these imports into your SBT console:

import cats.effect._, org.http4s._,
// import cats.effect._
// import org.http4s._
// import

Using the http4s-dsl, we can construct an HttpService by pattern matching the request. Let’s build a service that matches requests to GET /hello/:name, where :name is a path parameter for the person to greet.

val helloWorldService = HttpService[IO] {
  case GET -> Root / "hello" / name =>
    Ok(s"Hello, $name.")
// helloWorldService: org.http4s.HttpService[cats.effect.IO] = Kleisli(org.http4s.HttpService$$$Lambda$57714/1255774693@725636d4)

Returning content in the response

In order to return content of type T in the response an EntityEncoder[T] must be used. We can define the EntityEncoder[T] implictly so that it doesn’t need to be explicitly included when serving the response.

In the example below, we’re defining a tweetEncoder and then explicitly using it to encode the response contents of a Tweet, which can be seen as Ok(getTweet(tweetId))(tweetEncoder).

We’ve defined tweetsEncoder as being implicit so that we don’t need to explicitly reference it when serving the response, which can be seen as Ok(getPopularTweets()).

case class Tweet(id: Int, message: String)
// defined class Tweet

implicit def tweetEncoder: EntityEncoder[IO, Tweet] = ???
// tweetEncoder: org.http4s.EntityEncoder[cats.effect.IO,Tweet]

implicit def tweetsEncoder: EntityEncoder[IO, Seq[Tweet]] = ???
// tweetsEncoder: org.http4s.EntityEncoder[cats.effect.IO,Seq[Tweet]]

def getTweet(tweetId: Int): IO[Tweet] = ???
// getTweet: (tweetId: Int)cats.effect.IO[Tweet]

def getPopularTweets(): IO[Seq[Tweet]] = ???
// getPopularTweets: ()cats.effect.IO[Seq[Tweet]]

val tweetService = HttpService[IO] {
  case GET -> Root / "tweets" / "popular" =>
  case GET -> Root / "tweets" / IntVar(tweetId) =>
// tweetService: org.http4s.HttpService[cats.effect.IO] = Kleisli(org.http4s.HttpService$$$Lambda$57714/1255774693@5aff25b5)

Running your service

http4s supports multiple server backends. In this example, we’ll use blaze, the native backend supported by http4s.

We start from a BlazeBuilder, and then mount the helloWorldService under the base path of / and the remainder of the services under the base path of /api. The services can be mounted in any order as the request will be matched against the longest base paths first. The BlazeBuilder is immutable with chained methods, each returning a new builder.

Multiple HttpServices can be combined with the combineK method (or its alias <+>) by importing cats.implicits._ and org.http4s.implicits._.

import cats.implicits._
// import cats.implicits._

import org.http4s.server.blaze._
// import org.http4s.server.blaze._

import org.http4s.implicits._
// import org.http4s.implicits._

val services = tweetService <+> helloWorldService
// services:[[β$0$][cats.effect.IO,β$0$],org.http4s.Request[cats.effect.IO],org.http4s.Response[cats.effect.IO]] = Kleisli(org.http4s.instances.KleisliInstances$$anon$1$$Lambda$57728/1454269213@b0b7d2a)

val builder = BlazeBuilder[IO].bindHttp(8080, "localhost").mountService(helloWorldService, "/").mountService(services, "/api").start
// builder: cats.effect.IO[org.http4s.server.Server[cats.effect.IO]] = IO$1773690118

The bindHttp call isn’t strictly necessary as the server will be set to run using defaults of port 8080 and the loopback address. The mountService call associates a base path with a HttpService.

A builder can be run to start the server.

val server = builder.unsafeRunSync()
// server: org.http4s.server.Server[cats.effect.IO] = BlazeServer(/

Use curl, or your favorite HTTP client, to see your service in action:

$ curl http://localhost:8080/hello/Pete

Cleaning up

Our server consumes system resources. Let’s clean up by shutting it down:


Running your service as an App

Every ServerBuilder[F] has a .serve method that returns a Stream[F, Nothing]. This stream runs forever without emitting any output. When this process is run with .unsafeRun on the main thread, it blocks forever, keeping the JVM (and your server) alive until the JVM is killed.

As a convenience, http4s provides an org.http4s.util.StreamApp[F[_]] trait with an abstract main method that returns a Stream. A StreamApp runs the process and adds a JVM shutdown hook to interrupt the infinite process and gracefully shut down your server when a SIGTERM is received.

import fs2.Stream
// import fs2.Stream

import org.http4s.server.blaze._
// import org.http4s.server.blaze._

import org.http4s.util.StreamApp
// import org.http4s.util.StreamApp

import org.http4s.util.StreamApp.ExitCode
// import org.http4s.util.StreamApp.ExitCode

object Main extends StreamApp[IO] {
  override def stream(args: List[String], requestShutdown: IO[Unit]): Stream[IO, ExitCode] =
      .bindHttp(8080, "localhost")
      .mountService(helloWorldService, "/")
      .mountService(services, "/api")
// defined object Main