Skip to main content
Version: 2.x

Akka Http Interop

An interop module is provided for Akka Http 10.2.4

Installation

libraryDependencies ++= Seq(
"de.heikoseeberger" %% "akka-http-zio-json" % "1.36.0",
)

Usage

import akka.actor.ActorSystem
import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.model.HttpEntity
import akka.http.scaladsl.unmarshalling.Unmarshal
import de.heikoseeberger.akkahttpziojson.ZioJsonSupport
import zio.{ Task, ZIO }
import zio.json._

final case class Greeting(greeting: String)

object Greeting {
import ZioJsonSupport._

implicit val decoder: JsonDecoder[Greeting] =
DeriveJsonDecoder.gen[Greeting]

implicit val encoder: JsonEncoder[Greeting] =
DeriveJsonEncoder.gen[Greeting]

// automatically derived from the zio-json codecs

// implicit val akkaMarshaller: ToEntityMarshaller[Greeting] =
// implicitly[ToEntityMarshaller[Greeting]]
//
// implicit val akkaUnmarshaller: FromEntityUnmarshaller[Greeting] =
// implicitly[FromEntityUnmarshaller[Greeting]]

implicit val system = ActorSystem()

// under the hood, Akka Http uses marshallers and unmarshallers for Json http entities

def marshallGreeting(greeting: Greeting): Task[HttpEntity] =
ZIO.fromFuture(implicit ec => Marshal(greeting).to[HttpEntity])

def unmarshallGreeting(entity: HttpEntity): Task[Greeting] =
ZIO.fromFuture(implicit ec => Unmarshal(entity).to[Greeting])
}

Example project

A fully working example can be found here.