zio-http icon indicating copy to clipboard operation
zio-http copied to clipboard

Http client and json

Open larochef opened this issue 2 years ago • 3 comments

Is your feature request related to a problem? Please describe.

I'm doing a zio app that mostly proxifies another service and simplifies the api. I would have expected that working with json would be as easy as with other http tools, just defining some conf to select the json lib, configure encoders/decoders, and all done.

Having a server with a json api isn't too hard, but the client part required the following code to add the content-type to the request:

package zio.http.extended

import zio.*
import zio.http.*
import zio.json.*

object JsonBody {
  def apply[T: JsonEncoder](body: T): Body = {
    Body
      .fromString(body.toJson, Charsets.Utf8)
      .withContentType(MediaType.application.json)
  }

which means using some subpackage of zio.

Describe the solution you'd like Could it be possible to specify more simply the content-type with the body? Maybe the method to change the content type shouldn't be private[zio] ? Or is there some other way to create bodies that I haven't seen?

Also it would be nice to have an example for the client doing a post request in the doc.

Also, so far I find the integration with zio-json not as good as with the other json libs: I needed to use String as intermediate type all along, could there be a way to have some kind of higher level codec to use type classes and directly work with the case classes mapping to the request or response?

Thank you for your time.

Describe alternatives you've considered

Additional context

larochef avatar Jul 10 '23 14:07 larochef

I agree, as we already depend on zio-schema and zio-json for the endpoint API we could have constructors for Body/Request/Response directly using JsonCodec or Schema

vigoo avatar Jul 12 '23 09:07 vigoo

The body type hint should be public. I think this is being worked on in the hackathon now. 🤞

jdegoes avatar Jul 27 '23 12:07 jdegoes

I think we should add these to Body

constructors:

def json[T: Schema](body: T): Body

def json[T: zio.json.JsonEncoder](body: T): Body

parsers:

def asJson[T: Schema]: Either[String, T]

def asJson[T: zio.json.JsonDecoder]: Either[String, T]

vigoo avatar Jul 27 '23 13:07 vigoo