Skip to content

Javalin Java Framework: REST API Tutorial and Examples

Build a Javalin REST API in Java or Kotlin with routing, JSON, validation, error handling, WebSockets, and deployment examples for the lightweight framework.

Published Updated

Javalin is a lightweight Java and Kotlin web framework for REST APIs, WebSockets, and server-rendered applications. A minimal server needs only a Javalin instance, a route, and start(); the sections below build that foundation into a practical API.

Why Javalin?


Getting Started: Hello World in Java & Kotlin

1. Java Example

Add Maven dependency:

<dependency>
    <groupId>io.javalin</groupId>
    <artifactId>javalin</artifactId>
    <version>6.3.0</version> <!-- Check for latest version -->
</dependency>

Start the server:

import io.javalin.Javalin;

public class HelloWorld {
    public static void main(String[] args) {
        var app = Javalin.create().start(7070);
        app.get("/", ctx -> ctx.result("Hello from Java!"));
    }
}

Output:
Visit http://localhost:7070 in your browser. You’ll see:

Hello from Java!

2. Kotlin Example

Add Gradle dependency:

implementation("io.javalin:javalin:6.3.0")

Start the server:

import io.javalin.Javalin

fun main() {
    val app = Javalin.create().start(7070)
    app.get("/") { ctx -> ctx.result("Hello from Kotlin!") }
}

Output:
Visit http://localhost:7070:

Hello from Kotlin!

Key Features with Code Examples

1. Routing & Path Parameters

app.get("/greet/:name", ctx -> {
    String name = ctx.pathParam("name");
    ctx.result("Hello, " + name + "!");
});

Test:
http://localhost:7070/greet/Alice

Hello, Alice!

2. JSON Responses

app.get("/api/users", ctx -> {
    Map<String, Object> user = Map.of("id", 1, "name", "Bob");
    ctx.json(user); // Auto-converts to JSON
});

Output:

{"id":1,"name":"Bob"}

3. WebSocket (Real-Time Updates)

app.ws("/chat", ws -> {
    ws.onConnect(ctx -> System.out.println("Client connected!"));
    ws.onMessage(ctx -> {
        String message = ctx.message();
        ctx.send("Echo: " + message);
    });
});

Test:
Use a WebSocket client (e.g., browser dev tools) to connect to ws://localhost:7070/chat and send a message.


4. Async Handling

app.get("/async", ctx -> {
    ctx.future(() -> {
        Thread.sleep(1000); // Simulate delay
        return "Async response!";
    }).thenAccept(ctx::result);
});

Output (after 1 second):

Async response!

Conclusion

Javalin is ideal for developers who want a fast, unopinionated way to build web apps in Java/Kotlin. Its simplicity doesn’t compromise power—you can scale from tiny APIs to complex apps with plugins (e.g., OpenAPI, templating engines).

Next Steps:

Happy coding! 🚀


JavalinJavaKotlinWeb FrameworkREST APIWebSocketLightweightAsync