0

In the below example if i miss any field in the request body than it is giving the error in parsing as missing field. Can we anyway ignore it if the field is not present than it should not give error while parsing request. Also in response if the field is empty than it should not return those field in the response. How can we achieve this?

import sttp.tapir.generic.auto._
import sttp.tapir.json.circe.jsonBody
import sttp.tapir.server.ServerEndpoint
import sttp.tapir.{Endpoint, _}


case class Request{field1:String,field2:String}

case class Response{field1:String,field2:String}

 private lazy val reqBody = jsonBody[Request]
 

  private lazy val respBody = jsonBody[Response]

  private val postEP: Endpoint[Unit, (CommonHeader, Request), (StatusCode, ErrorInfo), (StatusCode, Response), Any] =
    baseEndpoint.post
      .in("test")
      .in(reqBody)
      .out(statusCode.and(respBody))
Gaël J
  • 11,274
  • 4
  • 17
  • 32

1 Answers1

2

If a field is optional, you should represent it as such in your model. The best way to do this is to use an Option type, e.g. as follows:

import sttp.tapir.generic.auto._
import sttp.tapir.json.circe.jsonBody
import sttp.tapir.server.ServerEndpoint
import sttp.tapir.{Endpoint, _}

case class Request(field1: Option[String], field2: Option[String])

case class Response(field1: Option[String], field2: Option[String])

private lazy val reqBody = jsonBody[Request]
private lazy val respBody = jsonBody[Response]

private val postEP: Endpoint[Unit, (CommonHeader, Request), (StatusCode, ErrorInfo), (StatusCode, Response), Any] =
    baseEndpoint.post
      .in("test")
      .in(reqBody)
      .out(statusCode.and(respBody))

The optional fields can either have the value of Some(value) or None.

adamw
  • 8,038
  • 4
  • 28
  • 32