portfolio-project-259-crystal
Project 259: Crystal Ruby-Like Compiled Language Todo Service API
A fast, elegantly written REST API implementation built with Crystal and the Kemal web framework. This demonstrates Crystal's philosophy of combining Ruby's beautiful syntax with compile-time type safety and C-like performance.
Architecture Overview
Crystal Characteristics
- Ruby-Like Syntax: Familiar, expressive, readable code
- Statically Typed: Type inference from usage
- Compiled to Native: Generates LLVM IR, then native code
- Fast: Performance comparable to C/C++
- Memory Safe: Automatic memory management
- Concurrent: Lightweight green threads (fibers)
- Expressive: First-class functions and macros
- Pragmatic: Focus on developer happiness
- Strong Type System: Catches errors at compile time
- Interoperable: Call C libraries directly
Crystal Strengths
- Beauty and Performance: Ruby syntax with C speed
- Type Inference: Powerful without explicit annotations
- Concurrency: Green threads (fibers) for scalability
- Metaprogramming: Macros for code generation
- Compilation: Fast compile times with caching
- Memory: Efficient with automatic management
- Interoperability: Direct FFI to C libraries
- Error Handling: Compile-time null safety
- Standard Library: Rich and well-designed
- Tooling: Good IDE support and formatter
Development Tools
- Shards: Package manager for Crystal
- Kemal: Web framework for REST APIs
- Crystal Compiler: Compiles to native code
- VS Code: Editor support via plugins
- Crystal Format: Code formatter
- Crystal Playground: Interactive environment
Project Structure
project-259-crystal/
├── shard.yml # Crystal package manifest
├── src/
│ └── main.cr # HTTP server and application logic
├── .gitignore # Git ignore patterns
└── README.md # This file
Concepts
This project demonstrates fast, elegant REST API showing:
User Management (Type-Safe, Performant)
- View all users (hash table operations with sorting)
- View user by ID (optional type with safe access)
- Create user (not shown, easily extendable)
- Update user (efficient in-place mutations)
- Delete user (O(1) removal)
Todo Management (Compiled, Fast)
- View all todos (optimized collection operations)
- View todo by ID (direct hash access)
- Create todo (struct initialization)
- Update todo (mutable updates)
- Delete todo (efficient removal)
Health Check
- Health status (instant response)
Building and Running
Prerequisites
- Crystal 1.10+ compiler
- Shards package manager
Install Crystal
# macOS (via Homebrew)
brew install crystal
# Ubuntu/Debian
curl -fsSL https://crystal-lang.org/install.sh | sudo bash
# Windows
# Download from https://crystal-lang.org/
# Verify installation
crystal --version
shards --version
Build Project
cd project-259-crystal
shards install
crystal build src/main.cr -o bin/todo-api --release
Run Server
crystal src/main.cr
# or run the compiled binary
./bin/todo-api
The server will start on http://127.0.0.1:8080
Example Usage
Start Server:
$ crystal src/main.cr
Starting Todo API server (Crystal with Kemal)...
Initial users: 2
Initial todos: 2
Server listening on 127.0.0.1:8080
Check Health:
$ curl http://127.0.0.1:8080/health
{"status":"healthy","service":"todo-api","language":"crystal"}
Get All Users:
$ curl http://127.0.0.1:8080/users
[{"id":1,"name":"Alice Johnson","email":"alice@example.com"},...]
Get User by ID:
$ curl http://127.0.0.1:8080/users/1
{"id":1,"name":"Alice Johnson","email":"alice@example.com"}
Delete User:
$ curl -X DELETE http://127.0.0.1:8080/users/2
{"message":"User deleted"}
Key Crystal Concepts Demonstrated
- Structs: Value types for data structures
- Type Inference: Compiler deduces types from usage
- Optional Types: ? for nullable values
- Hash Tables: Efficient key-value storage
- String Interpolation: #{variable} in strings
- JSON Serialization: include JSON::Serializable
- Array Operations: sort_by and other methods
- Control Flow: if/unless/case expressions
- Methods: First-class functions
- Classes and Modules: Code organization
Crystal Features (Ruby-Like Compiled Language)
- Type Inference: Automatic type deduction
- Union Types: Multiple possible types
- Generics: Generic programming without repetition
- Macros: Compile-time code generation
- Fibers: Lightweight green threads
- Pattern Matching: Match on type and structure
- Operator Overloading: Custom operators
- Property Accessors: Automatic getters/setters
- Module Mixins: Code reuse through modules
- Exception Handling: Structured error handling
Use Cases
Crystal excels at:
- High-performance web servers
- System utilities and tools
- Microservices and REST APIs
- Real-time applications
- Data processing and ETL
- Command-line applications
- Game development
- Cross-platform tools
- Applications needing Ruby syntax with C performance
- Concurrent systems
Architectural Patterns
JSON Serializable Structs
struct User
include JSON::Serializable
property id : Int32
property name : String
property email : String
end
# Automatic serialization/deserialization
user.to_json # => JSON string
User.from_json(json_string)
Optional Type Handling
def get_user(id : Int32) : User?
@users[id]?
end
# Usage with safe navigation
if user = APP_STATE.get_user(id)
env.response.content_type = "application/json"
user.to_json
else
env.response.status_code = 404
ErrorResponse.new(error: "User not found").to_json
end
Kemal Route Definitions
get "/users/:id" do |env|
id = env.params.url["id"].to_i
if user = APP_STATE.get_user(id)
env.response.content_type = "application/json"
user.to_json
else
env.response.status_code = 404
ErrorResponse.new(error: "User not found").to_json
end
end
Efficient State Management
class AppState
getter users : Hash(Int32, User)
def get_all_users : Array(User)
@users.values.sort_by(&.id)
end
def delete_user(id : Int32) : Bool
@users.delete(id).nil? ? false : true
end
end
Crystal Unique Features
- Compiled with Type Inference: Ruby syntax, C performance
- Fiber-Based Concurrency: Lightweight green threads
- Macros: Powerful compile-time code generation
- Union Types: Express alternatives elegantly
- Optional Chaining: Safe navigation with ?
- C Interoperability: Direct FFI bindings
- Operator Definitions: Custom operators
- Splat Operators: Variable arguments
- Block Syntax: Flexible block handling
- Method Missing: Dynamic method handling
Performance & Characteristics
- Compilation: Fast (seconds to minutes)
- Startup: Very fast (native binary)
- Runtime: Very fast (comparable to C/C++)
- Memory: Efficient (automatic GC)
- Concurrency: Fibers for millions of light threads
- Type Checking: Compile-time with inference
- Binary Size: Small compiled binaries
- Interoperability: Excellent C support
- Learning Curve: Easy for Ruby developers
- Maturity: Production-ready (since 2014)
Crystal Programming Model
Crystal emphasizes:
- Developer Happiness: Ruby-like syntax
- Performance: C/C++ level speed
- Type Safety: Catch errors at compile time
- Concurrency: Fibers for scalability
- Expressiveness: Beautiful, readable code
- Pragmatism: Get things done effectively
- Metaprogramming: Powerful macros
- Simplicity: Familiar syntax
- Reliability: Fewer runtime errors
- Speed: Both compile and runtime
Comparison with Other Languages
Crystal differs strategically:
- Syntax: Ruby-like (vs C-like)
- Performance: C/C++ equivalent (vs interpreted)
- Type System: Inferred, not explicit
- Compilation: Single-step native (vs bytecode)
- Memory: Automatic GC (vs manual)
- Concurrency: Fibers (vs threads)
- Learning: Easy for Ruby devs (vs steep)
- Expressiveness: Very high (vs verbose)
- Metaprogramming: Powerful macros (vs limited)
- Philosophy: Beauty and performance together
When to Use Crystal
Best for:
- High-performance REST APIs
- Web servers and microservices
- System utilities and tools
- Real-time applications
- Data processing pipelines
- Command-line tools
- Concurrent systems
- Applications needing Ruby readability with C speed
- Teams with Ruby experience
- Performance-critical applications
Libraries and Dependencies
Web Framework
kemal- Lightweight web frameworkjson- JSON serialization
Utilities
http- HTTP utilitiesuri- URL parsing
Development
shards- Package managercrystal- Language and toolchain
Testing Example
def test_get_user
user = User.new(id: 1, name: "Alice", email: "alice@example.com")
assert user.id == 1
assert user.name == "Alice"
end
Dependencies
Core platform:
- Crystal Compiler: 1.10+
- Shards: Package manager
- Kemal: Web framework
- LLVM: For code generation
This project demonstrates Crystal's philosophy: combine Ruby's beautiful, expressive syntax with compile-time type safety and native performance for systems that are both elegant and fast.
Ruby-Inspired Performance Innovation
Crystal approach to language design:
- Beauty First: Ruby-like syntax for happiness
- Performance: Compile to native for speed
- Type Safety: Inference without annotations
- Concurrency: Fibers for millions of tasks
- Metaprogramming: Powerful compile-time macros
- Pragmatism: Get real work done
- Interoperability: Call C libraries directly
- Tooling: Fast compilation and good IDE support
- Community: Active, welcoming Rubyist community
- Reliability: Catch errors at compile time
The implementation showcases Crystal's mission: provide a language that gives developers the joy and expressiveness of Ruby while delivering the performance and reliability of C/C++—enabling creation of fast, maintainable systems that are both beautiful to write and fast to execute.
portfolio-project-259-crystal
- 0
- 0
- 0
- 0
- 2
- 3 days ago
- June 13, 2026
Sat, 13 Jun 2026 12:50:25 GMT