Skip to content

Instantly share code, notes, and snippets.

@saschpe
Last active April 23, 2020 08:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saschpe/84b31cb88005c0b72f8239c8f5584308 to your computer and use it in GitHub Desktop.
Save saschpe/84b31cb88005c0b72f8239c8f5584308 to your computer and use it in GitHub Desktop.
class Api(
userAgent: String,
val apiKey: String
) {
val client = HttpClient {
install(JsonFeature) {
serializer = KotlinxSerializer(Json.nonstrict)
}
install(Logging) {
logger = Logger.DEFAULT
level = LogLevel.HEADERS
}
install(UserAgent) { agent = userAgent }
}
fun fullUrl(path: String) = "$API_URL$API_BASE_PATH$path"
suspend inline fun <reified T> get(
path: String,
block: HttpRequestBuilder.() -> Unit = {}
): T = client.get(fullUrl(path)) { parameter("key", apiKey); block() }
suspend inline fun <reified T> put(
path: String,
block: HttpRequestBuilder.() -> Unit = {}
): T = client.put(fullUrl(path)) { parameter("key", apiKey); block() }
suspend inline fun <reified T> post(
path: String,
block: HttpRequestBuilder.() -> Unit = {}
): T = client.post(fullUrl(path)) { parameter("key", apiKey); block() }
suspend inline fun <reified T> delete(
path: String,
block: HttpRequestBuilder.() -> Unit = {}
): T = client.delete(fullUrl(path)) { parameter("key", apiKey); block() }
companion object {
private const val API_URL = "https://example.com/"
private const val API_BASE_PATH = "v01/"
}
}
fun HttpRequestBuilder.headerAuthorization(token: String) =
header(HttpHeaders.Authorization, "Bearer $token")
fun HttpRequestBuilder.headerContentTypeJson() =
header(HttpHeaders.ContentType, ContentType.Application.Json)
fun HttpRequestBuilder.headerAcceptJson() =
header(HttpHeaders.Accept, ContentType.Application.Json)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment