Here is the code to bind request param to the router.
val testReader: Endpoint[Test] = Endpoint.derive[Test].fromParams
val test: Endpoint[String] = post("test" ? testReader) { t : Test => {
Created("OK")
}}
I am using the method fromParams. This method can bind request parameters in a very cool way. However, I dont konw which similiar way I can bind request body in the finch
Many thanks in advance
For the sake of providing a complete working example I'll assume a case class like this:
And some requests like this:
Now when you write the following…
What's happening is that Finch is using generic derivation (powered by Shapeless) to determine (at compile time) how to parse the query params as a
Test. You can then test the endpoint like this:Which will print:
Here I'm using Circe's generic derivation to automatically encode the "created"
Testas JSON for the response.You can also use Circe to derive a reader for the request body:
This is almost exactly the same as
testabove, but we're usingbodyto get anEndpoint[String]that will read the request body and thenasto specify that we want the content parsed as JSON and decoded as aTestvalue. We can test this new version like this:And we'll get the answer we expect again.
In general when you want to read a certain kind of information of an incoming request, you'll use one of the basic
Endpoints provided by Finch (see the docs for a more complete list), and then use methods likeas,map, etc. on theEndpointto turn it into the shape you need.