scalaavroavro-toolsavro4s

Generate avsc avro schema from a scala case class at build


I want to generate an avro schema from a scala case class.

Suppose I have the following scala case class :

case class User(name : String, favorite_number: Int, favorite_color: String)

The related avro schema is :

{"namespace": "example.avro",
 "type": "record",
 "name": "User",
 "fields": [
     {"name": "name", "type": "string"},
     {"name": "favorite_number",  "type": "int"},
     {"name": "favorite_color", "type": "string"}
 ]
}

Is there a way to generate at build time, the avro scehma ? using sbt for example ? I saw sbt-avro4s that permit to build a scala class from an avro schema, but I need to do the inverse.

Thanks in advance for your help


Solution

  • Avro4s contains the logic to generate an Avro Schema from a case class.

    https://github.com/sksamuel/avro4s#schemas

    Following the project example:

    import com.sksamuel.avro4s.AvroSchema
    
    case class User(name : String, favorite_number: Int, favorite_color: String)
    val userSchema = AvroSchema[User]
    

    Hopefully that provides enough to get started on a sbt task if needed.