portfolio-project-204-crystal
Project 204: Crystal Todo Service API
A REST API service built with Crystal, a compiled language with Ruby-like syntax that combines developer joy with performance, static type checking, and memory safety, using Kemal, a lightweight, fast web framework for building efficient web applications.
Architecture Overview
Crystal Characteristics
- Ruby-Like Syntax: Clean, readable code familiar to Ruby developers
- Compiled Language: Compiles to efficient native machine code
- Static Typing: Type checking at compile-time with inference
- Performance: Near C-like performance with high-level syntax
- Memory Safety: Safe memory management without garbage collection overhead
- Concurrency: Lightweight fibers for concurrent operations
- Macros: Compile-time code generation and metaprogramming
- Type Inference: Automatic type deduction reduces annotations
- Standard Library: Rich built-in libraries
- Zero-Cost Abstractions: High-level features with no runtime overhead
Kemal Framework Features
- Lightweight: Minimal HTTP server abstraction
- Fast: High-performance request handling
- Simple Routing: Easy route definition with DSL
- Request/Response: Direct access to request data
- JSON Support: Built-in JSON serialization
- Middleware: Simple middleware pipeline
- Streaming: Efficient streaming support
- WebSocket: Real-time WebSocket support
- Error Handling: Exception handling with type safety
- Production Ready: Used in production applications
Crystal Runtime Features
- Compiled Execution: Direct native code execution
- Performance: Near C/C++ performance
- Memory Efficiency: Efficient memory usage
- Type Safety: Compile-time type verification
- Concurrency: Lightweight fibers
- Fiber Support: Non-blocking I/O with fibers
- GC Optional: Garbage collection available but not always needed
- Cross-Platform: Compile to Windows, macOS, Linux
- LLVM Backend: Generates optimized code via LLVM
- C Interop: Call C libraries directly
Project Structure
project-204-crystal/
├── shard.yml # Crystal project configuration
├── src/
│ └── main.cr # Complete application
├── .gitignore # Git ignore patterns
└── README.md # This file
API Concepts
This project demonstrates Crystal/Kemal for REST API development showing:
User Management
- List all users (
GET /api/users) - Get user by ID (
GET /api/users/{id}) - Create user (
POST /api/users) - Update user (
PUT /api/users/{id}) - Delete user (
DELETE /api/users/{id})
Todo Management
- List all todos (
GET /api/todos) - Get todo by ID (
GET /api/todos/{id}) - Create todo (
POST /api/todos) - Update todo (
PUT /api/todos/{id}) - Delete todo (
DELETE /api/todos/{id})
Health Check
- Health status (
GET /api/health)
Building and Running
Prerequisites
- Crystal 1.9.0 or later
- Shards package manager (included with Crystal)
Get Dependencies
cd project-204-crystal
shards install
Build
shards build
Run
crystal run src/main.cr
The service will start on http://0.0.0.0:8080
Release Build
crystal build src/main.cr --release -o build/todo-api
./build/todo-api
Testing Endpoints
# Health check
curl http://localhost:8080/api/health
# List users
curl http://localhost:8080/api/users
# Create user
curl -X POST http://localhost:8080/api/users \
-H "Content-Type: application/json" \
-d '{"name":"Charlie","email":"charlie@example.com"}'
# Get user by ID
curl http://localhost:8080/api/users/1
# Update user
curl -X PUT http://localhost:8080/api/users/1 \
-H "Content-Type: application/json" \
-d '{"name":"Alice Updated","email":"alice.updated@example.com"}'
# Delete user
curl -X DELETE http://localhost:8080/api/users/3
# List todos
curl http://localhost:8080/api/todos
# Get todo by ID
curl http://localhost:8080/api/todos/1
Example Output
Health Check:
{"status":"healthy","service":"todo-api","language":"crystal-kemal"}
List Users:
[
{"id":1,"name":"Alice Johnson","email":"alice@example.com"},
{"id":2,"name":"Bob Smith","email":"bob@example.com"}
]
Create User:
{"id":3,"name":"Charlie Brown","email":"charlie@example.com"}
List Todos:
[
{"id":1,"title":"Learn Crystal","description":"Master compiled language with Ruby syntax","completed":false,"user_id":1},
{"id":2,"title":"Build API","description":"Create web service","completed":true,"user_id":2}
]
Key Crystal Concepts Demonstrated
- Classes with Type Annotations: Explicit type declarations
- JSON Serializable: Automatic JSON encoding/decoding via macros
- Type Inference: Automatic type detection in assignments
- Closures: Blocks and closures with type safety
- Array Methods:
find,index,reject!operations - Class Variables:
@@variablefor shared state - Class Methods:
self.methodfor static methods - String Interpolation: Clean template literals
- Nil Safety:
?operator for optional types - Try/Rescue: Exception handling with type safety
Crystal Features (Compiled Language)
- Ruby Syntax: Familiar syntax for Ruby developers
- Compiled: Generates efficient native code
- Static Typing: Type checking at compile-time
- Type Inference: Reduces explicit type annotations
- Performance: Near C/C++ speeds
- Memory Safety: Safe without GC overhead
- Concurrency: Lightweight fiber support
- Macros: Compile-time code generation
- Nil Safety: Type system prevents nil errors
- C Interop: Call C/C++ libraries directly
Use Cases
Crystal/Kemal excels at:
- High-performance REST APIs
- Real-time applications (WebSockets)
- Microservices architecture
- System tools and utilities
- Data processing pipelines
- Competitive performance applications
- Web services with clean syntax
- Cloud-native applications
- High-concurrency services
- Systems programming with high-level syntax
Architectural Patterns
Classes with Type Annotations
class User
include JSON::Serializable
property id : Int32
property name : String
property email : String
end
Class Variables for State
@@users : Array(User) = [...]
@@next_user_id : Int32 = 3
Class Methods for Operations
def self.find_user(id : Int32) : User?
@@users.find { |u| u.id == id }
end
JSON Serialization
include JSON::Serializable
user.to_json
User.from_json(body)
Kemal Routes
get "/api/users" do |env|
env.response.content_type = "application/json"
AppState.get_users.to_json
end
Crystal Unique Features
- Ruby Syntax with Performance: Clean syntax with C-like speed
- Compile-Time Safety: Catch errors before runtime
- Type Inference: Reduces boilerplate type annotations
- Fiber-Based Concurrency: Lightweight async operations
- Macros: Powerful compile-time metaprogramming
- C Interop: Call C libraries directly
- Memory Efficiency: Control over memory without GC pauses
- LLVM Backend: Generates optimized code
- Zero-Cost Abstractions: High-level features with no overhead
- Standard Library: Rich built-in functionality
Performance Characteristics
- Startup: Fast with compiled binaries
- Memory: Efficient memory usage
- Throughput: High request throughput
- Latency: Low-latency request handling
- Binary Size: Small compiled binaries
- Compilation: Fast incremental compilation
- Runtime: Native code performance
- Scalability: Good horizontal scaling
Crystal Programming Model
Crystal emphasizes:
- Happiness: Ruby-like syntax for developer joy
- Performance: Compiled to efficient native code
- Type Safety: Static typing with inference
- Simplicity: Clean, expressive language design
- Clarity: Readable code without boilerplate
- Efficiency: Memory and CPU efficiency
- Pragmatism: Practical balance of features
- Community: Growing Crystal community
Comparison with Other Compiled Languages
Crystal differs from similar languages:
- vs Ruby: Compiled vs interpreted, static vs dynamic
- vs Rust: Easier syntax vs safer ownership system
- vs Go: Ruby-like syntax vs Go's simplicity
- vs C++: High-level syntax vs low-level control
- vs Java: Compilation target vs bytecode
When to Use Crystal/Kemal
Best for:
- High-performance REST APIs
- Teams familiar with Ruby
- Real-time applications (WebSockets)
- Microservices with performance requirements
- System tools and utilities
- Data processing pipelines
- Applications needing clean syntax with speed
- Cloud-native services
- Competitive performance scenarios
- Web services with type safety
Libraries and Dependencies
Core Dependencies
kemal- Web framework library- Crystal Standard Library - Built-in modules
Build Tools
Crystal- Language compilerShards- Package managerLLVM- Code generation backend
Core Concepts
Type Annotations
property id : Int32
property name : String
JSON Serializable
class User
include JSON::Serializable
end
Class Methods
def self.find_user(id : Int32) : User?
@@users.find { |u| u.id == id }
end
Closure Blocks
@@users.find { |u| u.id == id }
@@users.reject! { |u| u.id == id }
Optional Types
def find_user(id : Int32) : User?
Dependencies
Core platform:
- Crystal 1.9+: Language and compiler
- Shards: Package manager
- Kemal: Web framework library
- LLVM: Code generation
This project demonstrates Crystal's unique position as a compiled language with Ruby-like syntax and near C-like performance, proving that developer joy and high performance are not mutually exclusive. Perfect for teams that love Ruby's expressiveness but need the speed and type safety of compiled languages for production systems.
portfolio-project-204-crystal
- 0
- 0
- 0
- 0
- 1
- about 4 hours ago
- June 13, 2026
Sat, 13 Jun 2026 11:29:46 GMT