portfolio-project-235-crystal

Project 235: Crystal Todo Service API

A REST API service built with Crystal, a compiled language with Ruby-like syntax that prioritizes performance while maintaining developer productivity, using Kemal, a lightweight and performant web framework.

Architecture Overview

Crystal Characteristics

  • Ruby-Like Syntax: Familiar, expressive syntax inspired by Ruby
  • Statically Typed: Type inference without explicit annotations
  • Compiled: Compiles to native code via LLVM
  • Performance: Near-C performance with GC
  • Type Safety: Strong compile-time type checking
  • Null Safety: Union types prevent null pointer errors
  • Memory Safe: Automatic memory management
  • Fast Startup: Quick application startup
  • Small Binaries: Efficient executable size
  • Interoperability: C FFI support

Kemal Framework Features

  • Lightweight: Minimal framework overhead
  • Fast: High performance with async I/O
  • Expressive: Clean DSL for routing
  • Type Safe: Full type checking
  • Middleware: Built-in middleware support
  • JSON Support: Native JSON serialization
  • Error Handling: Comprehensive error management
  • Streaming: Efficient streaming support
  • Testing: Easy to test with pure functions
  • Production Ready: Used in production systems

Crystal Runtime Features

  • LLVM Compilation: Native code generation
  • Garbage Collection: Automatic memory management
  • Concurrency: Fibers for lightweight concurrency
  • Pattern Matching: Powerful case expressions
  • Type System: Strong, static typing
  • Macros: Compile-time code generation
  • Methods: Everything is a method (Ruby-like)
  • Classes: Full OOP with inheritance
  • Modules: Mixin support through modules
  • Standard Library: Rich built-in library

Project Structure

project-235-crystal/
├── shard.yml                                # Crystal package manifest
├── src/
│   └── app.cr                               # Application implementation
├── bin/                                     # Compiled binary (generated)
├── .gitignore                               # Git ignore patterns
└── README.md                                # This file

API Concepts

This project demonstrates Crystal 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.11 or later
  • LLVM development libraries

Install Crystal (macOS with Homebrew)

brew install crystal

Install Crystal (Ubuntu/Debian)

curl -sSL https://crystal-lang.org/install.sh | sudo bash

Build

cd project-235-crystal
crystal build src/app.cr --release -o bin/todo-api

Run

crystal run src/app.cr

Or run the compiled binary:

./bin/todo-api

The service will start on http://0.0.0.0:8080

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

# 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"}

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 web development","completed":false,"user_id":1},
  {"id":2,"title":"Build API","description":"Create web service","completed":true,"user_id":2}
]

Key Crystal Concepts Demonstrated

  1. Structs: Value types with compile-time guarantees
  2. Classes: Reference types for shared state
  3. Type Inference: Compiler deduces types automatically
  4. Union Types: Multiple possible types safely
  5. Pattern Matching: Exhaustive case expressions
  6. Methods: Uniform call syntax (everything is a method)
  7. Macros: Compile-time code generation
  8. Fibers: Lightweight concurrency primitives
  9. JSON Mapping: Automatic serialization
  10. Nil Safety: Union types prevent nil errors

Crystal Features (Ruby with Speed)

  • Performance: Compiled to native code, C-like speed
  • Syntax: Ruby-like familiarity with less boilerplate
  • Type Safety: Strong compile-time checking
  • Developer Experience: Fast iteration with clarity
  • Concurrency: Fibers for lightweight async
  • Interoperability: C FFI for library integration
  • Community: Growing ecosystem
  • Cross-Platform: Windows, Linux, macOS
  • Tooling: Good IDE support
  • Reliability: Used in production systems

Use Cases

Crystal excels at:

  • REST APIs and microservices
  • Web applications
  • Systems programming
  • Command-line tools
  • Data processing pipelines
  • Real-time systems
  • Game servers
  • Embedded systems
  • Performance-critical applications
  • Cross-platform applications

Architectural Patterns

Struct Definitions with JSON Mapping

struct User
  JSON.mapping(
    id: Int32,
    name: String,
    email: String
  )
end

Class-Based State Management

class AppState
  @@users = [...]
  @@lock = Mutex.new

  def self.get_users : Array(User)
    @@lock.synchronize { @@users.dup }
  end
end

Route Handlers with Type Safety

get "/api/users/:id" do |env|
  id = env.params.url["id"].to_i
  user = AppState.get_user_by_id(id)
  if user
    env.response.content_type = "application/json"
    user.to_json
  else
    env.response.status_code = 404
  end
end

Safe Nil Handling

name = data["name"]?.try(&.as_s) || "Default Name"

Type-Safe Method Composition

def create_user(name : String, email : String) : User
  # Implementation with type safety
end

Crystal Unique Features

  • Type Inference: Powerful deduction without annotations
  • Union Types: A | B for multiple possibilities
  • Nil Safety: Required explicit nil handling
  • Pattern Matching: Case with exhaustiveness checking
  • Macros: Compile-time code transformation
  • Fibers: M:N threading with async capabilities
  • Method Overloading: Multiple arities of same method
  • Splat Operators: *args and **kwargs
  • Blocks and Yields: Ruby-style closures
  • C Interoperability: Direct FFI support

Performance Characteristics

  • Startup: Very fast startup with compiled code
  • Memory: Efficient with GC and struct values
  • Throughput: Excellent request handling
  • Latency: Very low latency from native code
  • Compilation: Reasonable compilation time
  • Execution: Near-C native code performance
  • Scalability: Good with fibers and async
  • Development: Productive Ruby-like syntax
  • Production: Production-ready compilation

Crystal Programming Model

Crystal emphasizes:

  • Clarity: Ruby-like syntax for readability
  • Performance: Compiled to native code
  • Safety: Type checking at compile time
  • Productivity: Fast development cycles
  • Correctness: Strong guarantees at compile time
  • Efficiency: Small binaries, fast execution
  • Concurrency: Fiber-based lightweight async
  • Community: Growing, supportive community
  • Innovation: Modern language design
  • Pragmatism: Balance of safety and control

Comparison with Other Languages

Crystal differs from similar languages:

  • vs Ruby: Compiled, type-safe, better performance
  • vs Go: Ruby-like syntax, different concurrency
  • vs Rust: No borrow checker, automatic memory safety
  • vs Python: Compiled, type-safe, better performance
  • vs Nim: Different syntax, similar compilation approach

When to Use Crystal

Best for:

  • REST APIs and web services
  • Web applications
  • Systems programming
  • Command-line tools
  • Performance-critical applications
  • Microservices
  • Data processing pipelines
  • Real-time systems
  • Applications needing Ruby productivity with C performance
  • Projects valuing both speed and code clarity

Libraries and Dependencies

Core Dependencies

  • kemal - Web framework
  • json - JSON serialization (standard library)

Additional Libraries Available

  • amber - Full-stack web framework
  • lucky - Modern web framework
  • granite - ORM framework
  • db - Database access
  • log - Logging framework
  • spec - Testing framework
  • uuid - UUID generation
  • time - Time handling

Core Concepts

Struct and Class Definitions

struct User
  property id : Int32
  property name : String
  property email : String
end

class Database
  @@users = [] of User
  
  def self.add_user(user : User)
    @@users << user
  end
end

Type-Safe Methods

def greet(name : String) : String
  "Hello, #{name}!"
end

def process(users : Array(User)) : Array(String)
  users.map { |u| u.name }
end

Safe Nil Handling

value : String?
safe_value = value.try { |v| v.upcase } || "default"

Pattern Matching

case user
when User
  puts "User: #{user.name}"
when Nil
  puts "No user found"
end

Block and Iterator Usage

users.each do |user|
  puts user.name
end

names = users.map { |u| u.name }

Dependencies

Core platform:

  • Crystal 1.11+: Language and compiler
  • LLVM: Compilation backend
  • Kemal: Web framework

This project demonstrates Crystal's unique value proposition: Ruby's expressiveness and productivity with compiled performance. It's ideal for developers who want fast execution without sacrificing code clarity and developer experience.

Compiled Web Development

Crystal's approach to web services:

  • Performance: Compiled to native code with LLVM
  • Syntax: Ruby-like familiarity and clarity
  • Safety: Type checking at compile time
  • Efficiency: Small binaries and fast startup
  • Productivity: Fast development with type safety
  • Concurrency: Fiber-based async for scalability

The implementation showcases how Crystal enables developers to write web services with Ruby's familiar syntax while achieving the performance characteristics of compiled languages, making it ideal for performance-sensitive applications that demand developer productivity.

Repository

portfolio-project-235-crystal

Owner
Statistic
  • 0
  • 0
  • 0
  • 0
  • 2
  • 3 days ago
  • June 13, 2026
License

Links
Synced at

Sat, 13 Jun 2026 12:10:07 GMT

Languages