Technical Note: Using Circe with java.net.http

Brian Schlining
1 min readDec 22, 2024
Scala logo

Overview

There are a number of great HTTP request libraries that can be used in Scala. Some popular ones include sttp, okhttp, and requests, among many others. Since Java 11, the JDK includes a decent HTTP client and I often use it in my Scala applications.

Circe is a popular (and by far, my favorite) JSON encoder/decoder library for Scala. It’s very simple to use Circe to decode requests using java.net.http.HttpClient. I’ve outlined a simple working example below. The steps are:

  1. Use case classes to define your data model.
case class Names(items: List[String], limit: Int, offset: Int, total: Int)

2. Create implicit io.circe.Decoders for your case classes and bring them into scope.

given Decoder[Names] = deriveDecoder[Names]

3. Create a java.net.http.HttpResponse.BodyHandler that uses Circe to decode the JSON response body.

class CirceBodyHandler[T: Decoder] extends HttpResponse.BodyHandler[Either[Throwable, T]]:

override def apply(responseInfo: HttpResponse.ResponseInfo): HttpResponse.BodySubscriber[Either[Throwable, T]] =
HttpResponse
.BodySubscribers
.mapping(HttpResponse
.BodySubscribers…

--

--

Brian Schlining
Brian Schlining

Written by Brian Schlining

Polyglot coder. Deep-sea Researcher. Zazen aficionado. I think squids are pretty cool.

No responses yet