Link Search Menu Expand Document

Http Calls

Using the browser’s default fetch-api can get quite tiresome, which is why fritz2 offers a small wrapper for it:

First you create a Request which points to your endpoint url:

val usersApi = http("https://reqresss.in/api/users")
            .acceptJson()
            .contentType("application/json")

The remote service offers some convenience-methods to configure your API-calls, like the acceptJson() above which simply adds the correct header to each request sent using the template.

Sending a request is pretty straightforward:

val result: String = usersApi.get(s).getBody()

getBody() returns the body of the response as a String. Instead, you can also use some following methods to get different results:

  • getBlob(): Blob
  • getArrayBuffer(): ArrayBuffer
  • getFormData(): FormData
  • getJson(): Any?

If your request was not successful (Response.status != 200) a FetchException will be thrown.

The same works for posts and other methods, just use different parameters for the body to send.

Of course the remote service is primarily designed to use in your Handlers within your Stores when exchanging data with your backend:

val userStore = object : RootStore<String>("") {
    
    val usersApi = http("https://reqresss.in/api/users").acceptJson().contentType("application/json")

    val addUser = handle<String> { _, s : String ->
        usersApi.body("""
            {
                "name": "$s",
                "job": "programmer"
            }
        """.trimIndent())
        .post().getBody()
    }
}

You can use this Handler like any other to handle Flows of actions:

... 
render {
    div {
        ...
        button {
            +"add programmer"
            clicks.map {
                "just a name" // wherever you get this from...
            } handledBy userStore.addUser
        }
    }
}

// or
userStore.addUser("just a name")

To see a complete example of this, visit our remote example.

In the real world, instead of creating the JSON manually, better use kotlinx.serialization. Get inspired by our repositories example and use our repositories API.

You can easily setup your local webpack-server to proxy other services when developing locally in your build.gradle.kts:

kotlin {
    js {
        browser {
            runTask {
                devServer = org.jetbrains.kotlin.gradle.targets.js.webpack.KotlinWebpackConfig.DevServer(
                    port = 9000,
                    contentBase = listOf("$buildDir/distributions"),
                    proxy = mapOf(
                        "/myService" to "http://localhost:8080"
                    )
                )
            }
        }
    }
}

Want to do bidirectional communications? Keep on reading about Websockets.


Distributed by a MIT license.