https://kotlinlang.org logo
Docs
Join the conversationJoin Slack
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by Linen
http4k
  • d

    dave

    07/09/2021, 1:22 PM
    3,4 There's nothing to tie lenses to Http4k. You can write a custom lens implementation which unmarshalls the JSON 5 this will be tricky unless you can inject the http client manually into the connect client- then you'd provide a thin Http4k adapter wrapper - which is the pattern we use for the AwsSdkClient and AWS SDK v2z 6 see above 7 you can use an approver without the test runner wrapper. All the JsonApprovalTest does is to configure the approver and then inject it into the test case. The code is all there in the approval test module. Alternatively use OkeyDoke or JSONAssert. For the individual values - there are a couple of ways but nothing Http4k specific.
    g
    1 reply · 2 participants
  • a

    Andrew O'Hara

    07/09/2021, 5:11 PM
    Are there any digest auth client filters anywhere? I know there's an okhttp authenticator I can wrap into a filter, but it would be a pain.
    d
    r
    11 replies · 3 participants
  • s

    Stefan

    07/12/2021, 9:58 AM
    out of curiosity - why is this global RequestContexts store with a concurrent hashmap needed? Wouldn't it just be enough to attach an immutable
    Map<Key,Any>
    as context to each request?
    🤔 1
    a
    2 replies · 2 participants
  • n

    Norman

    07/12/2021, 4:05 PM
    Hey team, Is there a a built in or best practice way to handle graceful shutdowns?
    s
    5 replies · 2 participants
  • j

    Joseph Pickering

    07/13/2021, 12:00 PM
    hey team! is there a way of having an optional request body parameter?
    d
    r
    3 replies · 3 participants
  • a

    Andrew O'Hara

    07/18/2021, 5:58 PM
    The docs in https://github.com/http4k/http4k.github.io seem autogenerated. Is there another place we're supposed to contribute to the docs?
    1 reply · 1 participant
  • d

    dave

    07/21/2021, 5:46 PM
    Yes - this is exactly correct. For multiple examples to be rendered you need to provide all of them. It's a bit of a limitation.
    s
    7 replies · 2 participants
  • d

    dave

    07/27/2021, 9:26 AM
    The reason is because normally filters are only applied AFTER you match (in a routing context)
    r
    2 replies · 2 participants
  • d

    dave

    07/27/2021, 4:37 PM
    PSA - we've added search back into the http4k site - powered by Algolia. Hopefully it's useful - but feedback appreciated 😄
    🙌 3
    r
    r
    6 replies · 3 participants
  • c

    Cosmin Victor Celea

    08/05/2021, 6:17 PM
    Hi, is there a way to configure timeouts for requests?
    d
    j
    +1
    10 replies · 4 participants
  • r

    Razvan

    08/10/2021, 3:17 PM
    @dave I can't run the GraphQL example any idea why... I see you changed it not long ago... I copy pasted it move it in the right package yet still got:
    Exception in thread "main" java.lang.ExceptionInInitializerError
    	at guide.reference.graphql.TmpKt.main(Tmp.kt:32)
    	at guide.reference.graphql.TmpKt.main(Tmp.kt)
    Caused by: com.expediagroup.graphql.generator.exceptions.EmptyQueryTypeException: Invalid query object type - no valid queries are available.
    d
    16 replies · 2 participants
  • a

    andyg

    08/11/2021, 8:19 AM
    Hi... super impressed with how quickly you guys are able to add new integrations. Trying out the AWS Lambda by converting a working API. 2 questions... can it be run locally? There is no
    main()
    when the entry point is
    class HelloServerlessHttp4k : ApiGatewayV1LambdaFunction(http4kApp)
    . Also, how to import the
    LambdaHttpClient
    ? thank you
    s
    d
    8 replies · 3 participants
  • a

    andyg

    08/11/2021, 8:34 AM
    totally separate question - can you define a Lens with add'l function or post-processing? example:
    val myLens = Query.nonEmptyString().required("ids")...split(";")
    Within the route I can insert the request then add functions:
    myLens(myRequest).split(";")
    but is it possible to add the
    split
    to the Lens definition?
    s
    1 reply · 2 participants
  • r

    Razvan

    08/12/2021, 8:43 AM
    Hi, I'm getting a bit crazy here, any clue at what can go wrong ? (yep already invalidated caches) In a file got this contract route:
    private val bodyTokenResponseLens = Body.auto<TokenResponse>().toLens()
    
        fun createTokenRoute(): ContractRoute = "/token" meta {
            returning(OK, bodyTokenResponseLens to TokenResponse("A", "B", 1800))
        } bindContract <http://Method.POST|Method.POST> to createTokenHandler2()
        private fun createTokenHandler2(): HttpHandler = { req -> Response(OK) }
    try to use it in with a openApi3 render I get a
    Exception in thread "main" java.lang.NullPointerException
    	at org.http4k.contract.RouteMetaDsl.returningStatus(routeMeta.kt:85)
    	at org.http4k.contract.RouteMetaDsl.returningStatus$default(routeMeta.kt:83)
    If i comment the return line is all OK, if it take the code and move it in test class it runs...
    3 replies · 1 participant
  • r

    Razvan

    08/12/2021, 9:56 AM
    About OpenApi, if i create my one BasicAuthSecurity like copy paste of the existent one
    class FakeBasicAuthSecurity(realm: String,  credentials: Credentials, val name: String = "basicAuth") : Security {
            override val filter: Filter = ServerFilters.BasicAuth(realm, credentials )
            companion object
        }
    and I use it in
    security = FakeBasicAuthSecurity("Backbone", Credentials("tom", "jerry"))
    No Security is added generated spec, any reason why ?
    d
    3 replies · 2 participants
  • s

    Sean Abbott

    08/12/2021, 6:16 PM
    Hello, I'm new to this and having a little trouble wrapping my head around a basic concept. So I have the generated ExampleContractRoute,
    object ExampleContractRoute {
        // this specifies the route contract, including examples of the input and output body objects - they will
        // get exploded into JSON schema in the OpenAPI docs
        private val spec = "/echo" meta {
            summary = "echoes the name and message sent to it"
            receiving(nameAndMessageLens to NameAndMessage("jim", "hello!"))
            returning(OK, nameAndMessageLens to NameAndMessage("jim", "hello!"))
        } bindContract POST
    
        // note that because we don't have any dynamic parameters, we can use a HttpHandler instance instead of a function
        private val echo: HttpHandler = { request: Request ->
            val received: NameAndMessage = nameAndMessageLens(request)
            Response(OK).with(nameAndMessageLens of received)
        }
    
        operator fun invoke(): ContractRoute = spec to echo
    }
    which is being called inside contract in my app function
    "/" bind contract {
            renderer = OpenApi3(ApiInfo("Test API", "v1.0"), Jackson)
    
            // Return Swagger API definition under /swagger.json
            descriptionPath = "/swagger.json"
    
            // Add contract routes
            routes += ExampleContractRoute()
            routes += HealthRoute()
        },
    and I'm trying to add a nested route to the ExampleContract route, like
    /echo/excited
    just as a toy example What would be idiomatic way to do that?
    d
    13 replies · 2 participants
  • m

    Matt

    08/13/2021, 8:41 AM
    Hello all, is it possible to stack filters which apply to specific routes? For example, could I have a stack of BasicAuth filters, each for a specific route?
    d
    3 replies · 2 participants
  • g

    Gopal S Akshintala

    08/16/2021, 4:25 PM
    Hi, I am a newbie to serverless and this example from the documentation is very helpful: http4k Tutorial: Serverless http4k with AWS Lambda I am able to quickly deploy and understand the nuances. Thanks for this great library and documentation. Now I am looking for an example where a db is used with AWS lambda in Http4k, are there any sample codebases which can help? Thanks!
    d
    11 replies · 2 participants
  • m

    Matt

    08/18/2021, 11:21 AM
    Hello all, I have a simple ContractRoute based on the example in the docs (https://www.http4k.org/guide/reference/contracts/). If I send a request to the echo route with the Accept header set to application/xml I get the JSON response back. My expectation was that I would get a 406. I was also expecting to get a 405 if I try to make a request to a defined route using the wrong HTTP method. What do I need to do to implement this behaviour?
    d
    3 replies · 2 participants
  • s

    Sean Abbott

    08/23/2021, 7:16 PM
    So a few days ago, you said you'd suggest applying the correct filter to the correct route. Is that possible with a ContractRoute? I have
    fun partnerAccountTaskRoute(): ContractRoute {
        return spec to ::partnerAccountTaskHandler
    }
    fun partnerAccountTaskHandler(partnerAccountId: Long, task: String, taskType: String): HttpHandler = { request: Request ->
    ...
    }
    and
    fun validTaskTypeFilter() = Filter { next ->
    ...
    }
    but I can't figure out how to compose the
    spec to ::function
    with the filter on it
    d
    5 replies · 2 participants
  • a

    andyg

    08/27/2021, 9:55 AM
    One of my apps is hosted on Heroku and has one route that kicks off a long-running process. Heroku requires at least some data to be returned to the client within 30 seconds or it returns a timeout error. Is there a recommended pattern for periodically sending a small response back to the client (i.e. "waiting...") in order to avoid the connection timeout? I think this might be a case for using "server-sent events" but not sure how to integrate into a running route. thank you
    t
    j
    +1
    7 replies · 4 participants
  • b

    Bart

    08/28/2021, 6:02 PM
    Hi all, recently stumbled upon the http4k library and looking forward to try it in one of my pet projects!
    🙂 3
    d
    1 reply · 2 participants
  • j

    Jippe Holwerda

    09/08/2021, 9:26 AM
    Hi all. Question: I'm trying to stream a JDBC Blob as a response. The database transactions are handled in a http4k filter. However, when Jetty tries to create the HttpServletResponse and reads the Inputstream, we're not in the context of the http4k transaction filter anymore. At that point, the JDBC resultset is closed and the inputstream cannot be read anymore. Is there any way out of this?
    4 replies · 1 participant
  • v

    Vojtěch Knyttl

    09/09/2021, 3:00 PM
    We are using http4k with OpenApi doc generation with custom jackson. That is great as the examples in OpenApi are 100% equal to responses. However, this is not true for enum models. For example this enum model for DonutSize correctly show "example: d4" in lowercase (as we use jackson enum transformer to lowercase), but the individual enums are rendered uppercase. Is there something special we need to do for the enum models to be generated lowercase? Thanks!
    👍 1
    d
    5 replies · 2 participants
  • a

    Andrew O'Hara

    09/09/2021, 9:29 PM
    Actually, the
    +
    appears to be valid for
    application/x-www-form-urlencoded
    content such as query args, so http4k's implementation is valid. A workaround would still be great, if possible.
    s
    1 reply · 2 participants
  • s

    Sandymcp

    09/14/2021, 8:40 AM
    I have a question regarding frame size for web sockets, how does one set this?
    d
    3 replies · 2 participants
  • s

    Sandymcp

    09/22/2021, 12:07 PM
    Is it possible to serve SSE using KtorCIO?
    d
    6 replies · 2 participants
  • a

    Arnab

    09/30/2021, 11:20 AM
    I have the following code:
    object HelloWorldQueryHandler {
      fun hello(yourname: String) = "Hello $yourname"
    }
    
    class GraphQLHandler: GraphQLHandler {
      private val graphql = newGraphQL(
        toSchema(
          SchemaGeneratorConfig(supportedPackages = listOf("no.example.capgemini")),
          listOf(TopLevelObject(HelloWorldQueryHandler))
        )
      ).build()
    
      override fun invoke(request: GraphQLRequest): GraphQLResponse =
        GraphQLResponse.from(
          graphql.execute {
            Builder()
              .query(request.query)
              .variables(request.variables)
          }
        )
    }
    
    fun main() {
      val app = routes("/graphql" bind graphQL(GraphQLHandler()))
      app.asServer(Netty()).start()
    }
    Now, this works when I use the GraphQL playground, but not when I use the Graphiql client. For the Graphiql client, this just returns an empty response. Am I missing something? Why is there a difference?
    d
    22 replies · 2 participants
  • m

    MrNiamh

    10/04/2021, 7:09 PM
    heyo 👋 just a quick one - What is the correct way to remove the timeout for a websocket? Can't see it in the wshandler or websocket classes but am getting the following after the connection is chilling for a while:
    Error: org.eclipse.jetty.websocket.api.CloseException: java.util.concurrent.TimeoutException: Idle timeout expired: 300008/300000 ms
    d
    2 replies · 2 participants
  • s

    s4nchez

    10/05/2021, 1:48 PM
    Have you tried sending something back from the endpoint? eg:
    val sse = sse(
                "/hello" bind sse(
                    "/{name}" bind { sse: Sse ->
                        val name = sse.connectRequest.path("name")!!
                        sse.send(Event("event1", "hello $name", "123"))
                        sse.send(Event("event2", "again $name", "456"))
                        sse.send(Data("goodbye $name".byteInputStream()))
                    }
                )
            )
    s
    7 replies · 2 participants
Powered by Linen
Title
s

s4nchez

10/05/2021, 1:48 PM
Have you tried sending something back from the endpoint? eg:
val sse = sse(
            "/hello" bind sse(
                "/{name}" bind { sse: Sse ->
                    val name = sse.connectRequest.path("name")!!
                    sse.send(Event("event1", "hello $name", "123"))
                    sse.send(Event("event2", "again $name", "456"))
                    sse.send(Data("goodbye $name".byteInputStream()))
                }
            )
        )
s

Sandymcp

10/05/2021, 1:49 PM
Yes, and in the debugger it nver reaches this point, because, as I said , it’s not finding the handler
s

s4nchez

10/05/2021, 1:52 PM
Let me see if I can reproduce it.
@Sandymcp can you try the following curl?
curl --http2 -H "Accept:text/event-stream" <http://localhost:8080/test>
You example gives me NPE with a normal curl (as that’s not stating you want an event stream), but works with the command above.
s

Sandymcp

10/05/2021, 2:14 PM
Ok, but then it should return 406 not accepted?
and not a 500 and certainly not a 404 when there is a normal http handler present.
Ok I could put a filter in front of the SSE handler, catch the NPE and check the headers and return 406 myself. Of course if I were to need an http handler on the same port then Undertow would give me the unwanted 404/
View count: 3