softwaremill / softwaremill/tapir

oneOf inputs with different types for different formats

Open
#4,971 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

v2
Dominant language
Scala
Stars
1.5k
Forks
468
Avg merge
5h 37m
Merged PRs (30d)
34

Description

Hi, I have a situation where I'd like to vary the input type based on the media type - ordinarily I'd just use another endpoint but unfortunately this is a webhook so there's limited control over it. As in https://tapir.softwaremill.com/en/latest/endpoint/oneof.html#oneofbody-inputs-outputs, this works:

case class User(name: String)

object User {
  given Schema[User] = Schema.derived
}

val same = oneOfBody[User](
  formBody[User],
  multipartBody[User]
)

But if I need more information in the multipart case, for example:

case class User(name: String)

object User {
  given Schema[User] = Schema.derived
}

case class UserPart(name: Part[String])

object UserPart {
  given Schema[UserPart] = Schema.derived
}

val either = oneOfBody[Either[User, UserPart]](
  formBody[Either[User, UserPart]],
  multipartBody[Either[Part, UserPart]],
)

Then this fails to compile (I believe!) owing to no Codec for Part in the form case.

A workaround is to formBody[User].map[Either[User,UserPart]](_.asLeft)(either => either.fold(identity, throw new Exception("invalid format"))) but that's not so great 😅...

Intuitively I feel like:

val either: EndpointInput[Either[L, R]] = oneOfEither[L, R](
  formBody[L],
  multipartBody[R]
)

Would make sense, of course please point out if there is already a way to do this 😅, otherwise I guess consider this a feature request.

Thanks!

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the oneOfBody, formBody, multipartBody, and EndpointInput examples in the issue, then trace how input codecs are selected for each branch. Done means a form input using User and a multipart input using UserPart can be combined with branch-specific types without requiring a Part codec for the form case.

Written by the indexing model from the issue text.

Assessment

Tech stack
scala
Domain
api
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.