Search⌘ K

Models

Explore how to effectively reuse data models while implementing pure functional HTTP APIs in Scala. Understand how to add semi-automatic JSON codec derivation using the Circe library, as well as considerations for compile time and API stability when modifying model attributes.

We'll cover the following...

Recap

We will reuse the models that we have already written here.

To recap, these were our models:

Scala
final case class Translation(lang: LanguageCode, name: ProductName)
object Translation {
implicit val decode: Decoder[Translation] =
Decoder.forProduct2("lang", "name")(Translation.apply)
implicit val encode: Encoder[Translation] =
Encoder.forProduct2("lang", "name")(t => (t.lang, t.name))
}
type ProductId = java.util.UUID
final case class Product(id: ProductId, names: NonEmptySet[Translation])
object Product {
implicit val decode: Decoder[Product] =
Decoder.forProduct2("id", "names")(Product.apply)
implicit val encode: Encoder[Product] =
Encoder.forProduct2("id", "names")(p => (p.id, p.names))
}

Derive JSON codecs

The only thing we will change is add a semi-automatic derivation of the JSON codecs. We just need to import the appropriate Circe package and call the derive functions.