I am trying to define the following endpoint:
object WebApiEndpoints {
val geminiMarketData = endpoint.get
.in("ws")
.out(
webSocketBody[
String,
CodecFormat.TextPlain,
MarketDataResponse,
CodecFormat.Json
](ZioStreams)
)
}
I already have the zio json codecs in scope
given MarketDataResponseCodec: JsonCodec[MarketDataResponse] =
DeriveJsonCodec
.gen[MarketDataResponse]
and am getting an error asking for a
ttp.tapir.Codec[
Array[Byte],
MarketDataResponse,
sttp.tapir.CodecFormat.Json
]
However I cannot find an example in the documentation on how to derive this type automatically. I am seeing some reference to creating a schema but I am not sure how that relates when I already have the zio json codec.
I would like to avoid creating the codec manually if at all possible
adamw
January 27, 2025, 7:59am
2
Hello!
I added an example of a WS endpoint accepting and producing WS messages:
import sttp.tapir.ztapir.*
import sttp.tapir.{Codec, CodecFormat, PublicEndpoint}
import zio.http.{Response as ZioHttpResponse, Routes, Server}
import zio.json.{DeriveJsonDecoder, DeriveJsonEncoder, JsonDecoder, JsonEncoder}
import zio.stream.Stream
import zio.{ExitCode, URIO, ZIO, ZIOAppDefault, ZLayer}
// After running, try opening a ws connection to ws://localhost:8080/ws, sending some text messages, and then closing
// from the client-side.
object WebSocketZioHttpJsonServer extends ZIOAppDefault:
case class Input(a: Int, b: Int)
object Input:
given JsonDecoder[Input] = DeriveJsonDecoder.gen[Input]
given JsonEncoder[Input] = DeriveJsonEncoder.gen[Input]
case class Output(c: Int)
object Output:
given JsonDecoder[Output] = DeriveJsonDecoder.gen[Output]
given JsonEncoder[Output] = DeriveJsonEncoder.gen[Output]
It should be sufficient to import the Tapir Codec
s for ZIO JSON, using import sttp.tapir.json.zio.*
. Using this and the built-in implicits, a codec using them should be automatically built for WebSocketFrame
s: tapir/core/src/main/scala/sttp/tapir/Codec.scala at master · softwaremill/tapir · GitHub
1 Like