4.6 KiB
4.6 KiB
JokeAPI for Kotlin/Java
A simple Kotlin/Java library to retrieve jokes from Sv443's JokeAPI.
Examples (TL;DR)
import net.thauvin.erik.jokeapi.JokeApi.Companion.getJoke
val joke = getJoke()
val safe = getJoke(safe = true)
val pun = getJoke(category = Category.PUN)
The parameters match the joke endpoint.
A Joke
class instance is returned:
data class Joke(
val error: Boolean,
val category: Category,
val type: Type,
val joke: List<String>,
val flags: Set<Flag>,
val id: Int,
val safe: Boolean,
val language: Language
)
- View more examples...
If an error occurs, a JokeException
is thrown:
class JokeException(
val error: Boolean,
val internalError: Boolean,
val code: Int,
message: String,
val causedBy: List<String>,
val additionalInfo: String,
val timestamp: Long,
cause: Throwable? = null
) : Exception(message, cause)
If an HTTP error occurs an HttpErrorException
is thrown, with its message and cause matching the JokeAPI status codes:
class HttpErrorException(
val statusCode: Int,
message: String,
cause: Throwable? = null
) : IOException(message, cause)
- View more examples...
Gradle, Maven, etc.
To use with Gradle, include the following dependency in your build file:
dependencies {
implementation("net.thauvin.erik:jokeapi:0.9-SNAPSHOT")
}
Instructions for using with Maven, Ivy, etc. can be found on Maven Central.
Raw Joke
You can also retrieve a raw joke in all supported formats.
For example for YAML:
var joke = getRawJoke(format = Format.YAML, idRange = IdRange(22))
println(joke)
error: false
category: "Programming"
type: "single"
joke: "If Bill Gates had a dime for every time Windows crashed ... Oh wait, he does."
flags:
nsfw: false
religious: false
political: false
racist: false
sexist: false
explicit: false
id: 22
safe: true
lang: "en"
- View more examples...
Java
To make it easier to use the library with Java, a configuration builder is also available:
var config = new JokeConfig.Builder()
.type(Type.SINGLE)
.safe(true)
.build();
var joke = JokeApi.getJoke(config);
for (var j : joke.getJoke()) {
System.out.println(j);
}
Extending
A generic apiCall()
function is available to access other JokeAPI endpoints.
For example to retrieve the French language code:
val lang = apiCall(
endPoint = "langcode",
path = "french",
params = mapOf(Parameter.FORMAT to Format.YAML.value)
)
println(lang)
error: false
code: "fr"
- View more examples...