Spaces:
Sleeping
Sleeping
KevanSoon
commited on
Commit
·
e2dd470
1
Parent(s):
872e5c6
added javalin endpoints in main.java
Browse files
demo/src/main/java/com/example/Main.java
CHANGED
|
@@ -1,11 +1,53 @@
|
|
| 1 |
package app;
|
| 2 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import io.javalin.Javalin;
|
| 4 |
|
| 5 |
public class Main {
|
| 6 |
public static void main(String[] args) {
|
| 7 |
Javalin app = Javalin.create()
|
|
|
|
|
|
|
| 8 |
.get("/", ctx -> ctx.result("Hello from Javalin on Hugging Face Spaces!"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
.start(7860);
|
| 10 |
}
|
| 11 |
}
|
|
|
|
| 1 |
package app;
|
| 2 |
|
| 3 |
+
import java.net.URI;
|
| 4 |
+
import java.net.http.HttpClient;
|
| 5 |
+
import java.net.http.HttpRequest;
|
| 6 |
+
import java.net.http.HttpResponse;
|
| 7 |
+
|
| 8 |
import io.javalin.Javalin;
|
| 9 |
|
| 10 |
public class Main {
|
| 11 |
public static void main(String[] args) {
|
| 12 |
Javalin app = Javalin.create()
|
| 13 |
+
|
| 14 |
+
// Endpoint 1: The original root endpoint
|
| 15 |
.get("/", ctx -> ctx.result("Hello from Javalin on Hugging Face Spaces!"))
|
| 16 |
+
|
| 17 |
+
// Endpoint 2: A dynamic endpoint that takes a name from the path
|
| 18 |
+
// Example: Accessing /hello/John will display "Hello, John!"
|
| 19 |
+
.get("/hello/{name}", ctx -> {
|
| 20 |
+
String name = ctx.pathParam("name"); // Extracts "name" from the URL path
|
| 21 |
+
ctx.result("Hello, " + name + "!");
|
| 22 |
+
})
|
| 23 |
+
|
| 24 |
+
// Endpoint 3: An endpoint that calls an external API
|
| 25 |
+
// This endpoint fetches a random fact and returns it.
|
| 26 |
+
.get("/random-fact", ctx -> {
|
| 27 |
+
// Use Java's built-in HttpClient to make the API call
|
| 28 |
+
HttpClient client = HttpClient.newHttpClient();
|
| 29 |
+
HttpRequest request = HttpRequest.newBuilder()
|
| 30 |
+
.uri(URI.create("https://uselessfacts.jsph.pl/api/v2/facts/random?language=en"))
|
| 31 |
+
.build();
|
| 32 |
+
|
| 33 |
+
try {
|
| 34 |
+
// Send the request and get the response
|
| 35 |
+
// We ask for the response body as a String
|
| 36 |
+
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
|
| 37 |
+
|
| 38 |
+
// Set the response header to indicate the content is JSON
|
| 39 |
+
ctx.header("Content-Type", "application/json");
|
| 40 |
+
// Return the body from the external API call
|
| 41 |
+
ctx.result(response.body());
|
| 42 |
+
|
| 43 |
+
} catch (Exception e) {
|
| 44 |
+
// If the API call fails, return a server error status and message
|
| 45 |
+
ctx.status(500);
|
| 46 |
+
ctx.result("{\"error\": \"Failed to fetch a random fact.\"}");
|
| 47 |
+
}
|
| 48 |
+
})
|
| 49 |
+
|
| 50 |
+
// Start the server on the port configured for Hugging Face Spaces
|
| 51 |
.start(7860);
|
| 52 |
}
|
| 53 |
}
|