A Kotlin Multiplatform library that provides a single, unified API surface over multiple Lemmy server versions (0.18+, 0.19+, 1.0+). Consumers call one interface (LemmyApiBaseController) and receive unified ("uni") datatypes regardless of which Lemmy version the target instance is running.
Built with Ktor (HTTP), kotlinx.serialization (JSON), and targets JVM, Android, iOS, macOS, Linux, Windows, and JS.
LemmyApiClient().use { client ->
val api = client.connect(
instance = LemmyInstance("voyager.lemmy.ml"),
auth = LemmyAuth.Bearer(token),
).getOrThrow()
val site = api.getSite().getOrThrow()
// Some features are version dependent, so check support first.
if (api.FF.instanceBlock()) {
api.userBlockInstanceCommunities(...).getOrThrow()
}
// Enum entries can differ between API versions.
api.getSupportedEntries<SortType>()
}LemmyApiBaseController represents one instance, its resolved version, and its authentication. Change credentials explicitly after login or token refresh with api.updateAuth(LemmyAuth.Bearer(token)); use api.clearAuth() after logout.
You can also supply any Ktor HttpClient. Its engine and configuration are retained, while the library adds the plugins required for Lemmy requests:
val httpClient = HttpClient(OkHttp) {
install(Logging)
}
val client = LemmyApiClient(
httpClient = httpClient,
options = LemmyApiOptions(
requestTimeout = 20.seconds,
maxRetries = 5,
userAgent = "MyApp/1.0",
versionPolicy = VersionPolicy.LatestKnownCompatible,
),
)
val api = client.connect(LemmyInstance("voyager.lemmy.ml")).getOrThrow()Keep the client open while using controllers connected through it. A supplied HttpClient remains caller-owned and must be closed by the caller; when no client is supplied, LemmyApiClient owns and closes its default client.
Use connectForVersion(LemmyInstance(...), LemmyVersion(...)) when the server version is already known.
implementation("it.vercruysse.lemmyapi:lemmy-api:VERSION")It is currently in beta.
LemmyApiClient (options, optional caller-owned HttpClient)
└─ connect / connectForVersion (typed instance, auth, version) → LemmyApiBaseController
│
└─ version-specific LemmyApiUniWrapper (implements LemmyApiBaseController)
├─ LemmyApiController (raw Ktor HTTP calls, version-specific datatypes)
├─ Transformer (maps version-specific ↔ unified datatypes)
└─ MapperGenerator (interface) (declares all toUni/fromUni signatures)
The intention is to provide an easy-to-use API that supports a wide range of Lemmy instances. The backwards compatibility is achieved by transforming the requests and responses to a "universal" type. And by allowing you to check if a feature is supported by the instance. That way you can change the behavior of your app depending on the instance's version.
It is a non-goal to provide a stable API. The API can change with every iteration without warning nor deprecation.
- JVM datatypes implement
Serializable - Android datatypes implement
ParcelableandSerializable