kotlinhttp4k

How do you model a path parameter in the middle with http4k


I am using http4k-contracts and I am trying to model a route with a path parameter in the middle of the path, i.e.

This is the path: /player/{id}/match

This is my code (does not compile): "/player/" / Path.string().of("id") / "match" meta { ..

Whats the right way to do it?


Solution

  • If this doesn't compile, it probably means that the function on the end of that statement doesn't have enough parameters. You need something like this - notice the "dead" parameter in the middle of the lambda where the string "foo" would be injected:

    "/prefix" / Path.of("first") / "foo" / Path.of("second") 
        bindContract GET to { first, _, second -> { 
            Response(OK).body("$first $second") }
        }
    

    Trailing parameters work in exactly the same way, so by extrapolation you'd need this:

    val route = "/prefix" / Path.of("first") / "foo" meta { description = "I am great"} bindContract GET to { first, _ -> { Response(OK).body(first) } }
    

    For adding the meta tags, you can easily get tripped up by the infix whitespace, so try playing with the line breaks if it doesn't compile.