softwaremill / softwaremill/tapir
[Question] Handling empty query params
Nobody has claimed this yet.
- Dominant language
- Scala
- Stars
- 1.5k
- Forks
- 468
- Avg merge
- 5h 37m
- Merged PRs (30d)
- 34
Description
I am using Tapir in combination with an HTMX frontend.
Sending a GET request from an input field, HTMX will include the input as a query parameter, even if the value is empty, in some cases - it seems like this is purposefully replicating HTML form behavior.
E.g., I have a date input and use the date pickers "clear" button to reset the value. HTMX will issue a request to mypath?date=.
Tapir does not like this, I get a 400 - Invalid value for: query parameter date.
My endpoint looks something like this:
baseSiteEndpoint.get
.in(header[Option[Boolean]]("HX-Request"))
.in("mypath")
.in(query[Option[LocalDate]]("date"))
I would have expected this to yield a None. My IDE suggests, that this query param uses Codec.listHeadOption and I assume with Codec.localDate as underlying codec.
This seems to try to do something similar to strings.map(LocalDate.parse).headOption, in the sense that the LocalDate.parse fails bc. it might receive an empty string.
This does not work:
implicit val localDateOpt: Codec[String, Option[LocalDate], TextPlain] =
Codec.string.map(s => if (s.isEmpty) None else Some(LocalDate.parse(s)))(o => o.map(DateTimeFormatter.ISO_LOCAL_DATE.format).getOrElse(""))
.schema(Schema.schemaForLocalDate.asOption)
I don't understand the codec selection fully, so I'm a bit at a loss.
Also, I wonder if this behavior by Tapir is correct? It seems like many servers do accept query params of that sort?
Tapir version: 1.10.10
Scala version: 2.13.14
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the endpoint with the query string ?date= and trace how query[Option[LocalDate]]("date") selects and applies its codec. Compare that behavior with the supplied custom codec and determine whether an empty value should decode as None; done means the behavior is clarified or corrected and covered by an appropriate test.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- scala
- Domain
- api, backend
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100