Anyone experienced with http4k? I'm trying to add ...
# http4k
r
Anyone experienced with http4k? I'm trying to add routes with documentation but for somereason the routes are not getting registered?
Copy code
kt
    val contract = contract {
        renderer = OpenApi3(ApiInfo("Tasks API", "v0.1.0"), Argo)
        descriptionPath = "/docs"

        routes += UserRouter(userService).routes // these dont work
        routes += "/ping" bindContract Method.GET to { _ -> Response(Status.OK).body("pong") } // this works
    }

    val handler = routes("/api" bind contract)
    handler.asServer(Jetty(port)).start() ..

//....

class UserRouter(private val services: UserService) {

    val routes: List<ContractRoute> = listOf(
                "/users/{id}" meta {
            summary = "Get user details"
            returning(
                Status.BAD_REQUEST to "Invalid id",
                Status.NOT_FOUND to "User not found"
            )
        } bindContract GET to ::getUser,
a
Defining a
ContractRoute
with a path parameter would typically look like
Copy code
"/users" / idLens meta {
  ...
} bindContract GET to { id ->
  { req ->
    ...
  }
}
I'm not entirely sure if the contract router is unable to route for non-contract path parameters, but fixing that would be the first thing to try.
You can also try adding another route inside the contract that doesn't have a path parameter, as a quick sanity check
r
ok i was able to do it like this:
Copy code
"/users" / <http://Path.int|Path.int>().of("id") meta {
            summary = "Get user details"
            returning(
                Status.BAD_REQUEST to "Invalid id",
                Status.NOT_FOUND to "User not found"
            )
        } bindContract GET to { id ->
            {
                getUser(id)
            }
        },

// ...

    private fun getUser(userId: Int): Response = errorHandler {
        val res = services.getUser(userId)

        Response(Status.OK)
            .header("content-type", "application/json")
            .body(Json.encodeToString(res))
    }
Isnt there any possible way to still make the lambda receive request parameter?
or do i have to
getUser(id, it)
Copy code
"/users" / <http://Path.int|Path.int>().of("id") meta {
            summary = "Get user details"
            returning(
                Status.BAD_REQUEST to "Invalid id",
                Status.NOT_FOUND to "User not found"
            )
        } bindContract GET to { id -> { req ->
                getUser(req, id)
            }
        },
idk, this looks a bit awful
a
Does this give you what you need?
Copy code
bindContract GET to { id ->
  { req ->
    getUser(id)
  }
}
r
yes, it just looks weird, another problem i am having is for example defining this route:
users/{id}/boards
image.png
adding
/ "boards"
after the path... id thing is throwing error at the whole code
Copy code
val test = "/users" / <http://Path.int|Path.int>().of("id") / "boards" meta {
        summary = "Get the list with all user available boards"
        returning(
            Status.OK to "User boards",
            Status.BAD_REQUEST to "Invalid id",
            Status.NOT_FOUND to "User not found"
        )
    } bindContract GET to ::getUserBoards
this is getting casted to
Copy code
Pair<ContractRouteSpec2<Int, String>.Binder, KFunction1<Request, Response>>
(?)
instead of ContractRoute
a
If you see little benefit in having your path parameters provided by the contract handler in a typesafe manner, then you can omit the extra layer by adding an explicit
Request
type parameter to
req
Copy code
"/foo" / idLens meta {
  ...
} bindContract GET to { req: Request ->
  Response(OK)
}
The issue with the new route you've added is that you're not handling the value of the new
boards
parameter (even though it's not a lens).
Copy code
val test = "/users" / <http://Path.int|Path.int>().of("id") / "boards" meta {
  ...
} bindContract GET to { id, _ ->
  { req ->
    Response(OK)
  }
}
Notice the
_
parameter added after
id
. Since we don't care about its value, it can be named
_
and ignored
You may also want to share the id
PathLens
between routes, rather than redefine it each time you add a new route.
r
What does "Lens" mean in this case?
a
Copy code
val idLens: BiDiPathLens<Int> = <http://Path.int|Path.int>().of("id")
A lens is a typesafe way to get data in and out of an http message (ie request or response). So to share it, you would so something like:
Copy code
val getUser = "/users" / idLens bindContract GET
val putUser = "/users" / idLens bindContract PUT
The benefit is that you can reuse the lens in other contracts or in a client call
Copy code
val response = getUser
  .newRequest(hostname)
  .with(idLens of 123)
  .let(httpHandler)
260 Views