Skip to content

Json field OpenAPI #3830

@fokot

Description

@fokot

Is your feature request related to a problem? Please describe.
I have case class with Json field. I'm using Schema[Json] from zio.schema.codec.json._ to accept any json (object, number, string etc.) but in the generated OpenAPI I see that the type of json field is string. I think for this use case it would be better if the type would be json object

type: object
additionalProperties: true

Here is the code

import zio.*
import zio.http.*
import zio.http.codec.*
import zio.http.codec.PathCodec.*
import zio.http.endpoint.*
import zio.http.endpoint.openapi.*
import zio.json.{DeriveJsonDecoder, DeriveJsonEncoder, JsonDecoder, JsonEncoder}
import zio.json.ast.Json
import zio.schema.{DeriveSchema, Schema}
import zio.schema.annotation.description
import zio.schema.codec.json._


case class TestClass(
  name: String,
  json: Json
)

object TestClass {
  given Schema[TestClass] = DeriveSchema.gen[TestClass]
  given JsonDecoder[TestClass] = DeriveJsonDecoder.gen[TestClass]
  given JsonEncoder[TestClass] = DeriveJsonEncoder.gen[TestClass]
}

object Main extends ZIOAppDefault:

  val jsonFieldEndpoint =
    Endpoint(RoutePattern.GET / "json-field")
      .in[TestClass]
      .out[TestClass]

  val jsonFieldRoute = jsonFieldEndpoint.implementHandler(handler { (tc: TestClass) => ZIO.succeed(tc).debug("json-field") })

  def run: ZIO[ZIOAppArgs & Scope, Throwable, Unit] =
    for
      _ <- Console.printLine(s"Starting ZIO-HTTP server. Open http://localhost:8080/docs/openapi")
      openAPI = OpenAPIGen.fromEndpoints(
        title = "API",
        version = "1.0.0",
        jsonFieldEndpoint,
      )
      swaggerRoutes = SwaggerUI.routes(path("docs") / "openapi", openAPI)
      allRoutes = Routes(jsonFieldRoute) ++ swaggerRoutes
      process <- Server.serve(allRoutes).provide(Server.default)
    yield ()

Describe the solution you'd like
Custom handlind for Schema[Json] which will render

type: object
additionalProperties: true

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions