zio / zio-http

A next-generation Scala framework for building scalable, correct, and efficient HTTP clients and servers
https://zio.dev/zio-http
Apache License 2.0
787 stars 396 forks source link

Http client and json #2287

Open larochef opened 1 year ago

larochef commented 1 year ago

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

vigoo commented 1 year ago

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

jdegoes commented 1 year ago

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

vigoo commented 1 year ago

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]