Skip to content

Enitsed/kotlin-playground

Repository files navigation

Kotlin API Servers - Learning Guide

Welcome! This project contains two complete REST API server examples built with Kotlin to help you transition from TypeScript/NestJS/Express to Kotlin/JVM ecosystem.

🎯 Project Overview

You'll find two fully-functional API servers:

  1. Ktor API Server - Lightweight, modern, async-first framework
  2. Spring Boot API Server - Enterprise-grade, feature-rich framework with MySQL integration

Both implement the same Users REST API for easy comparison.

πŸ“ Project Structure

kotlin-example/
β”œβ”€β”€ ktor-api-server/                 # Ktor example (lightweight)
β”‚   β”œβ”€β”€ src/main/kotlin/
β”‚   β”‚   └── Application.kt           # All-in-one application file
β”‚   β”œβ”€β”€ build.gradle.kts
β”‚   β”œβ”€β”€ Dockerfile
β”‚   β”œβ”€β”€ README.md
β”‚   └── gradlew                      # Gradle wrapper
β”‚
β”œβ”€β”€ spring-boot-api-server/          # Spring Boot example (enterprise)
β”‚   β”œβ”€β”€ src/main/kotlin/com/example/
β”‚   β”‚   β”œβ”€β”€ Application.kt           # Spring Boot main class
β”‚   β”‚   β”œβ”€β”€ controller/              # REST endpoints
β”‚   β”‚   β”œβ”€β”€ service/                 # Business logic
β”‚   β”‚   β”œβ”€β”€ repository/              # Database access
β”‚   β”‚   β”œβ”€β”€ entity/                  # Database models
β”‚   β”‚   β”œβ”€β”€ dto/                     # API request/response objects
β”‚   β”‚   └── exception/               # Error handling
β”‚   β”œβ”€β”€ src/main/resources/
β”‚   β”‚   β”œβ”€β”€ application.yaml         # Default config
β”‚   β”‚   β”œβ”€β”€ application-dev.yaml     # Dev config
β”‚   β”‚   └── application-prod.yaml    # Prod config
β”‚   β”œβ”€β”€ build.gradle.kts
β”‚   β”œβ”€β”€ Dockerfile
β”‚   β”œβ”€β”€ docker-compose.yml           # MySQL container setup
β”‚   β”œβ”€β”€ init.sql                     # Database initialization
β”‚   β”œβ”€β”€ README.md
β”‚   └── gradlew                      # Gradle wrapper
β”‚
└── README.md                        # This file

πŸš€ Quick Start Guide

For Ktor (Simple, Lightweight)

cd ktor-api-server
./gradlew run
  • API runs on: http://localhost:8080
  • In-memory data storage (no database needed)
  • ~15 lines of main application code
  • Perfect for learning Kotlin fundamentals

For Spring Boot (Enterprise, Production-Ready)

Step 1: Start MySQL

cd spring-boot-api-server
docker-compose up -d

Step 2: Build and Run

./gradlew bootRun
  • API runs on: http://localhost:8080
  • MySQL database integration
  • Swagger UI: http://localhost:8080/swagger-ui.html
  • Full layered architecture (Controller β†’ Service β†’ Repository β†’ Entity)

πŸ”„ API Endpoints (Same for Both Projects)

Both APIs implement the same Users REST API:

Method Endpoint Description
GET /api/v1/users Get all users
GET /api/v1/users/{id} Get specific user
POST /api/v1/users Create new user
PUT /api/v1/users/{id} Update user
DELETE /api/v1/users/{id} Delete user
GET /api/v1/health Health check

Example: Get All Users

Ktor:

curl http://localhost:8080/api/v1/users

Spring Boot:

curl http://localhost:8080/api/v1/users

Same endpoint, different implementation!

Example: Create User

curl -X POST http://localhost:8080/api/v1/users \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Alice Johnson",
    "email": "alice@example.com",
    "age": 25
  }'

πŸ“š Learning Path

Week 1: Learn Ktor

  • Read ktor-api-server/README.md
  • Run ./gradlew run and test endpoints
  • Study Application.kt - understand the routing DSL
  • Learn Kotlin coroutines basics
  • Compare with your Express.js experience

Week 2: Learn Spring Boot

  • Start MySQL with docker-compose up -d
  • Read spring-boot-api-server/README.md
  • Run ./gradlew bootRun
  • Explore Swagger UI at /swagger-ui.html
  • Study the layered architecture (controller β†’ service β†’ repository)
  • Learn Spring annotations (@RestController, @Service, @Repository, etc.)
  • Compare with your NestJS experience

Week 3: Compare and Deepen

  • Run both servers side-by-side
  • Make the same API calls to both
  • Study the differences in structure
  • Modify code to add new endpoints
  • Experiment with validation and error handling

🧭 Framework Comparison

Ktor vs Express.js

Express.js:                  Ktor:
app.get('/')       β†’         get { }
app.post('/')      β†’         post { }
Middleware         β†’         Plugins/Install
req.body           β†’         call.receive()
res.json()         β†’         call.respond()
Promises/async     β†’         Coroutines

Spring Boot vs NestJS

NestJS:                      Spring Boot:
@Controller()      β†’         @RestController
@Get()             β†’         @GetMapping()
@Injectable()      β†’         @Service
@Inject()          β†’         @Autowired
ValidationPipe     β†’         @Valid + validators
Global filter      β†’         @ControllerAdvice

πŸ›  Technology Stack

Ktor Project

  • Framework: Ktor 2.3.6
  • Language: Kotlin 1.9.21
  • Runtime: Netty (async)
  • Serialization: kotlinx.serialization
  • Build: Gradle with Kotlin DSL
  • JVM: Java 17+

Spring Boot Project

  • Framework: Spring Boot 3.1.6
  • Language: Kotlin 1.9.21
  • Database: MySQL 8.0
  • ORM: Hibernate/JPA
  • Validation: Jakarta Bean Validation
  • Documentation: Springdoc OpenAPI (Swagger)
  • Build: Gradle with Kotlin DSL
  • JVM: Java 17+

πŸ“– Key Kotlin Concepts to Learn

  1. Data Classes: Immutable objects with auto-generated methods

    data class User(val id: Long, val name: String)
  2. Coroutines: Lightweight threading for async programming

    suspend fun fetchUser(): User { ... }
  3. Extension Functions: Add methods to existing classes

    fun String.isValidEmail(): Boolean { ... }
  4. Sealed Classes: Type-safe error handling

    sealed class Result<T> {
        data class Success<T>(val data: T) : Result<T>()
        data class Error<T>(val error: String) : Result<T>()
    }
  5. Scope Functions: Clean object initialization

    user.apply { name = "Updated" }
         .also { println(it) }

πŸ§ͺ Testing the APIs

Manual Testing with Curl

Get all users:

curl http://localhost:8080/api/v1/users

Create user:

curl -X POST http://localhost:8080/api/v1/users \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Bob Smith",
    "email": "bob@example.com",
    "age": 30
  }'

Update user:

curl -X PUT http://localhost:8080/api/v1/users/1 \
  -H "Content-Type: application/json" \
  -d '{"name": "John Updated", "age": 31}'

Delete user:

curl -X DELETE http://localhost:8080/api/v1/users/1

Using Swagger UI (Spring Boot Only)

Open browser: http://localhost:8080/swagger-ui.html

You can test all endpoints directly from the web interface!

πŸ“ File Organization Pattern

Ktor (Single File)

// Application.kt contains:
- Data Models (@Serializable)
- Business Logic (UserStore)
- Routes (DSL style)

Good for: Learning, microservices, prototypes

Spring Boot (Layered)

controller/    β†’ HTTP layer (@RestController)
service/       β†’ Business logic (@Service)
repository/    β†’ Database access (Spring Data JPA)
entity/        β†’ Database models (@Entity)
dto/           β†’ API contracts (Request/Response)
exception/     β†’ Error handling (@RestControllerAdvice)

Good for: Enterprise apps, complex logic, large teams

🐳 Docker Support

Build Docker Images

Ktor:

cd ktor-api-server
docker build -t ktor-users-api .
docker run -p 8080:8080 ktor-users-api

Spring Boot:

cd spring-boot-api-server
docker build -t spring-boot-users-api .
docker run -p 8080:8080 spring-boot-users-api

Using Docker Compose for Spring Boot

cd spring-boot-api-server
docker-compose up -d        # Start MySQL
docker-compose down         # Stop MySQL

πŸ”§ Configuration Profiles (Spring Boot)

Default Profile

./gradlew bootRun
# Uses: application.yaml
# Database: users_db
# Logging: INFO

Development Profile

./gradlew bootRun --args='--spring.profiles.active=dev'
# Uses: application-dev.yaml
# Shows SQL queries
# More logging

Production Profile

./gradlew bootRun --args='--spring.profiles.active=prod'
# Uses: application-prod.yaml
# Less logging
# Swagger disabled

πŸ“Š Database Setup (Spring Boot Only)

Option 1: Docker Compose (Recommended)

cd spring-boot-api-server
docker-compose up -d

This automatically:

  • Starts MySQL 8.0
  • Creates databases
  • Loads sample data from init.sql

Option 2: Manual MySQL Setup

# If MySQL is already running locally
mysql -u root -p1234 < spring-boot-api-server/init.sql

Useful MySQL Commands

# Connect
mysql -u root -p1234

# View users
USE users_db;
SELECT * FROM users;

# Clear data
DELETE FROM users;

πŸŽ“ Learning Resources

Understanding Kotlin

  • Data Classes: Perfect for DTOs and models
  • Extension Functions: Can add methods to existing classes
  • Coroutines: Learn async/await alternative
  • Scope Functions: apply, also, let for clean code

Understanding Ktor

  • Routing DSL: Express-like syntax
  • Plugins: Similar to middleware
  • Serialization: Type-safe JSON handling
  • Coroutines First: Everything is async

Understanding Spring Boot

  • Dependency Injection: Automatic wiring with annotations
  • Repositories: JPA makes database queries simple
  • Services: Business logic separation
  • Controllers: HTTP request handling
  • Exception Handlers: Centralized error handling

πŸ’‘ Tips for Success

  1. Start Simple: Run Ktor first, it's simpler
  2. Compare Code: Look at both implementations
  3. Modify and Experiment: Change the code, see what happens
  4. Use Swagger: Test Spring Boot APIs through web UI
  5. Read Error Messages: Kotlin compiler is very helpful
  6. Check Logs: Spring Boot logs are detailed and informative
  7. Use Your IDE: IntelliJ IDEA has excellent Kotlin support
  8. Debug: Set breakpoints and step through code
  9. Document: Add comments to understand concepts

🚨 Common Issues

Port Already in Use

# Find process using port 8080
lsof -i :8080

# Kill the process
kill -9 <PID>

MySQL Connection Failed (Spring Boot)

# Start MySQL
docker-compose up -d

# Verify it's running
docker ps | grep mysql

Gradle Build Failed

# Clean and rebuild
./gradlew clean build

πŸ“ž Next Steps

After completing this learning guide:

  1. Add new endpoints: Create endpoints for products, posts, etc.
  2. Add authentication: Implement JWT token validation
  3. Add pagination: Support limit/offset for list endpoints
  4. Add filtering: Filter users by name, age, email
  5. Add sorting: Sort results by different fields
  6. Add caching: Implement response caching
  7. Add monitoring: Add metrics and tracing
  8. Add tests: Write unit and integration tests

πŸ“š File References

  • Ktor Implementation: See ktor-api-server/src/main/kotlin/Application.kt
  • Spring Boot Implementation: See files in spring-boot-api-server/src/main/kotlin/com/example/
  • Ktor Detailed Guide: See ktor-api-server/README.md
  • Spring Boot Detailed Guide: See spring-boot-api-server/README.md

🎯 Quick Command Reference

Ktor

cd ktor-api-server
./gradlew run                 # Start server
./gradlew build               # Build project
./gradlew clean               # Clean build

Spring Boot

cd spring-boot-api-server
docker-compose up -d          # Start MySQL
./gradlew bootRun             # Start server
./gradlew build               # Build project
./gradlew clean               # Clean build
./gradlew bootRun --args='--spring.profiles.active=dev'  # Dev mode

πŸ“„ License

These examples are provided for learning purposes.


Happy Learning! πŸŽ“

Start with Ktor, then move to Spring Boot. Take your time to understand each framework before moving to the next one.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors