0PricingLogin
Scala for Backend Engineering & Functional Programming · Lesson

JSON Endpoints

Combine http4s with Circe.

JSON via circe

http4s integrates JSON through the http4s-circe module, which bridges circe codecs to EntityDecoder and EntityEncoder. circe is the de facto functional JSON library for Scala.

You define Encoder and Decoder instances for your types and let http4s handle the wire format.

// build.sbt
// "org.http4s" %% "http4s-circe" % http4sV
// "io.circe"   %% "circe-generic" % circeV

Deriving Codecs

With circe-generic you derive codecs automatically using deriveEncoder/deriveDecoder or the @JsonCodec annotation. They map case-class fields to JSON keys by name.

Derivation needs codecs for every field type, recursively.

import io.circe.generic.semiauto._

case class User(id: Int, name: String)
implicit val enc = deriveEncoder[User]
implicit val dec = deriveDecoder[User]

All lessons in this course

  1. Routes and HttpRoutes
  2. Requests and Responses
  3. JSON Endpoints
  4. Serving the Application
← Back to Scala for Backend Engineering & Functional Programming