🎉 Try the public beta of the new docs site at algolia.com/doc-beta! 🎉
API client / Getting started / Initialize

Initialize the Kotlin API client

Before you can index your data or search your Algolia indices, you must initialize a search client with your application ID and API key. You can find both in your Algolia account.

If you’re building native apps for mobile devices, don’t include the API key directly in your source code. Because mobile apps aren’t updated as frequently, create API keys on your server and fetch them when the app starts.

Initialize the search client

The search client handles authentication and lets you manage your indices, for example, add data to them, or search them.

1
2
3
4
5
6
7
val client = ClientSearch(
  applicationID = ApplicationID("YourApplicationID"),
  apiKey = APIKey("YourWriteAPIKey")
)
val indexName = IndexName("your_index_name")

client.initIndex(indexName)

Replace your_index_name with the name of the index you want to use. You can find your existing indices in the Algolia dashboard or using the listIndices method. If the index doesn’t exist, a new, empty index is created locally. It’s created on Algolia’s servers only if you add records to the index.

Don’t use sensitive or personally identifiable information as your index name, including usernames, IDs, or email addresses. Index names are publicly shared.

Operations that are scoped to your Algolia application through the client are:

Operations scoped to an index are:

The Recommend, Personalization, Insights, and A/B testing APIs come with their own clients:

Usage notes

Type safety

Response and parameters objects are typed to provide extensive compile-time safety. For example, to initialize the API client without confusing application ID and the API key:

1
2
3
4
val appID = ApplicationID("YourApplicationID")
val apiKey = APIKey("YourWriteAPIKey")

val client = ClientSearch(appID, apiKey)

For example, to use typed attributes:

1
2
3
val color = Attribute("color")
val category = Attribute("category")
val query = Query(attributesToRetrieve = listOf(color, category))

Enumerated types are represented by sealed classes. This lets you quickly discover all possible values for each type. Each enumerated type includes Other to pass a custom value:

1
2
3
4
5
val query = Query()

query.sortFacetsBy = SortFacetsBy.Count
// query.sortFacetsBy = SortFacetsBy.Alpha
// query.sortFacetsBy = SortFacetsBy.Other("custom value")

Domain-specific language

The Kotlin API client lets you use a domain-specific language (DSL) to set parameters, configure your index, or use filters for your search:

Example for query parameters:

1
2
3
4
5
6
val query = query {
   attributesToRetrieve {
       +"color"
       +"category"
   }
}

Example for settings:

1
2
3
4
5
val settings = settings {
   attributesToSnippet {
       +"content"(10)
   }
}

Example for filters:

1
2
3
4
5
6
7
8
9
10
11
12
val query = query {
   filters {
       and {
           facet("color", "red")
           facet("category", "shirt")
       }
       orNumeric {
           range("price", 0 until 10)
           comparison("price", Equals, 15)
       }
   }
}

Serialization

The Kotlin API client uses the kotlinx serialization library.

Deserialize a search response

To deserialize results from a search response, use the deserialize extension functions.

1
2
3
4
5
6
7
8
@Serializable
data class Contact(
    val firstname: String,
    val lastname: String
)

val response = index.search()
val contacts: List<Contact> = response.hits.deserialize(Contact.serializer())

Deserialize response from getObject

To deserialize the response from getObject, pass serializer as a parameter.

1
2
3
4
5
6
7
8
9
@Serializable
data class Contact(
    val firstname: String,
    val lastname: String,
    override val objectID: ObjectID
) : Indexable

val objectID = ObjectID("myID1")
val contact: Contact = index.getObject(Contact.serializer(), objectID)

Serialize and deserialize any Kotlin object

Use the standard methods of the kotlinx serialization library.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Serializable
data class Contact(
    val firstname: String,
    val lastname: String
)

// Create a new JSON object
val json: JsonObject = buildJsonObject {
    put("firstname", "Jimmie")
    put("lastname", "Barninger")
}

// Transform the JSON object into a Kotlin object
val contact: Contact = Json.decodeFromJsonElement(Contact.serializer(), json)

// You can configure your own `Json` instance for custom options:
val JsonNonStrict = Json {
    ignoreUnknownKeys = true
    isLenient = true
    allowSpecialFloatingPointValues = true
}
val contactNonStrict: Contact = JsonNonStrict.decodeFromJsonElement(Contact.serializer(), json)

Handling exceptions

A successful HTTP call returns a typed response object:

1
val response: ResponseSearch = index.search()

To handle exceptions, use a try / catch block:

1
2
3
4
5
6
7
8
try {
    val response = index.search()
} catch (exception: AlgoliaApiException) {
    when (exception.httpErrorCode) {
        404 -> TODO()
        400 -> TODO()
    }
}

Use multiple catch blocks to handle different types of exceptions:

1
2
3
4
5
6
7
8
9
try {
    val response = index.search()
} catch (exception: AlgoliaRuntimeException) {
    TODO()
} catch (exception: IOException) {
    TODO()
} catch (exception: Exception) {
    TODO()
}

Coroutines

The Kotlin API client uses suspending functions for all HTTP calls. This means that you can call these functions only from a coroutine scope.

The following example starts a coroutine in the main thread, then performs the search HTTP call in another thread. You can change the search response from the main thread.

1
2
3
4
5
6
7
8
9
class Searcher : CoroutineScope {
    override val coroutineContext = SupervisorJob()

    fun search() {
        launch(Dispatchers.Main) {
            val response = withContext(Dispatchers.Default) { index.search() }
        }
    }
}

The Kotlin API client doesn’t run any HTTP calls on any particular thread. You need to define this explicitly using coroutines.

To learn more about coroutines, see the Kotlin documentation.

Waiting for operations

Many operations with Algolia are asynchronous. To wait for operations, use apply or run:

1
2
3
4
5
6
index.apply {
    setSettings(Settings()).wait()
}
client.run {
    multipleBatchObjects(listOf<BatchOperationIndex>()).waitAll()
}

The wait functions are suspense functions and should be called from coroutines.

Thread safety

The Kotlin API client is thread-safe. You can use SearchClient, AnalyticsClient, and InsightsClient in a multi-threaded environment.

Did you find this page helpful?