Technical Note: Using Circe with java.net.http
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:
- 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…