Kotlin API clients
The Kotlin API clients let you interact with Algolia’s APIs from your Java backend.
Install the library
All API clients are part of the algoliasearch-client-kotlin
package.
If you use Gradle, add the following to your build.gradle
file:
1
2
3
4
5
dependencies {
implementation 'com.algolia:algoliasearch-client-kotlin:3.5.0'
// You need to specify an engine for Ktor
runtimeOnly 'io.ktor:ktor-client-java:2.3.11'
}
For more information about available engines for Ktor, see Engines.
Alternatively, you can import the BOM package:
1
2
3
4
5
6
7
dependencies {
implementation platform("com.algolia:algoliasearch-client-kotlin-bom:3.5.0}")
// define dependencies without versions
implementation 'com.algolia:algoliasearch-client-kotlin'
runtimeOnly 'io.ktor:ktor-client-java'
}
For serializing Kotlin data objects to JSON,
add the serialization plugin to your build.gradle
file:
1
2
3
plugins {
id 'org.jetbrains.kotlin.plugin.serialization' version '2.0.0'
}
Test your installation
To test your installation, create a new Kotlin project in your favorite IDE and run a short program that adds a record to a test index, searches your index, and prints the results.
-
If you haven’t already, create an Algolia account.
-
Copy the following code into your IDE. Replace
ALGOLIA_APPLICATION_ID
andALGOLIA_API_KEY
with values from your account. Make sure to use an API key withaddObject
andsearch
permissions.Copy1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
package org.example import io.github.cdimascio.dotenv.Dotenv import com.algolia.client.api.SearchClient import com.algolia.client.extensions.waitTask import com.algolia.client.model.search.* import kotlinx.serialization.json.* suspend fun main() { val appID = "ALGOLIA_APPLICATION_ID" // API key with `addObject` and `search` ACL val apiKey = "ALGOLIA_API_KEY" val indexName = "ALGOLIA_INDEX_NAME" val client = SearchClient(appID, apiKey) // Create record (with autogenerated `objectID`) val record = buildJsonObject { put("objectID", "object-1") put("name", "test record") } // Add record to an index val addResponse = client.saveObject(indexName, record) // Wait until indexing is done client.waitTask(indexName, addResponse.taskID) // Search for 'test' val response = client.search( SearchMethodParams(requests = listOf( SearchForHits( indexName, query = "test" ) ) ) ) println(response) }
In production, don’t include your credentials in your code. Use environment variables instead.
-
Run the program.
If the program completed successfully, you’ll see the API response.
Next steps
You can view your new index in the Algolia dashboard.