portfolio-project-153-crystal

Project 153: Crystal Todo Service API

A fast, compiled REST API service built with Crystal, a statically-typed language with Ruby-like syntax that compiles to efficient native code with zero runtime overhead.

Architecture Overview

Crystal Characteristics

  • Static Typing: Type inference with compile-time safety
  • Ruby-like Syntax: Expressive syntax similar to Ruby but compiled
  • Compiled: Compiles to efficient native C code via LLVM
  • Zero Overhead: No garbage collection overhead in type checking
  • Fast Execution: Performance comparable to C/C++
  • Concurrent: Lightweight fibers for concurrency
  • Type Safe: Prevents entire classes of runtime errors
  • Interop: Can call C libraries directly

Crystal Language Features

  • Type Inference: Automatic type deduction from context
  • Classes and Structs: Object-oriented programming
  • Pattern Matching: Destructuring in assignments
  • Generics: Parameterized types for reusability
  • Blocks and Procs: First-class anonymous functions
  • Macros: Compile-time code generation
  • Modules: Mixins and code organization
  • Exception Handling: Type-safe error handling

Project Structure

project-153-crystal/
├── shard.yml                                 # Shards package configuration
├── src/
│   └── app.cr                                # Application implementation
├── .gitignore                                # Git ignore patterns
└── README.md                                 # This file

API Concepts (As Data Service)

This project demonstrates Crystal as a data service showing:

User Management

  • List all users
  • Get user by ID
  • Create user
  • Update user
  • Delete user

Todo Management

  • List all todos
  • Get todo by ID
  • Create todo
  • Update todo
  • Delete todo

Building and Running

Prerequisites

  • Crystal 1.9 or later
  • LLVM 10 or later (for compilation)

Run

cd project-153-crystal
shards install
crystal run src/app.cr

Or build and run:

shards build
./bin/todo-service

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

Testing Endpoints

# Health check
curl http://localhost:3000/health

# List users
curl http://localhost:3000/api/users

# Create user
curl -X POST http://localhost:3000/api/users \
  -H "Content-Type: application/json" \
  -d '{"id":0,"name":"Charlie","email":"charlie@example.com"}'

# Get user by ID
curl http://localhost:3000/api/users/1

# Update user
curl -X PUT http://localhost:3000/api/users/1 \
  -H "Content-Type: application/json" \
  -d '{"id":1,"name":"Alice Updated","email":"alice.updated@example.com"}'

# Delete user
curl -X DELETE http://localhost:3000/api/users/3

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

Key Crystal Concepts Demonstrated

  1. Type Inference: Automatic type deduction with compile-time safety
  2. JSON Mapping: JSON.mapping macro for serialization
  3. Classes: Object-oriented data structures with properties
  4. Type Safety: Compile-time nil checking and type checking
  5. String Interpolation: Embedded expressions in strings
  6. Array Methods: Functional operations like find, map, delete_at
  7. Mutex: Thread-safe access to mutable state
  8. Block Syntax: Ruby-like blocks with do...end

Language Features (Crystal 1.9+)

  • Type Inference: Automatic type deduction from usage
  • Static Typing: Compile-time type safety
  • Classes: Full object-oriented programming
  • Generics: Parameterized types with type parameters
  • Blocks and Yield: Functions with block parameters
  • Macros: Compile-time code generation
  • Pattern Matching: Destructuring assignments
  • Modules: Mixins for code reuse
  • Exception Handling: Type-safe error handling
  • Operator Overloading: Custom operator implementations
  • Method Definitions: Instance and class methods
  • Properties: Automatic getter/setter generation

Use Cases

Crystal excels at:

  • Building high-performance web services
  • Command-line tools and utilities
  • Systems programming with safety
  • Data processing pipelines
  • REST APIs and microservices
  • Real-time applications
  • IoT and embedded systems
  • DevOps and infrastructure tools

Architectural Patterns

JSON Serialization with Macros

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

Type-Safe Parameter Parsing

id = env.params.url["id"].to_i32?
if id.nil?
  # Handle invalid ID
else
  # Use id with known Int32 type
end

Thread-Safe State with Mutex

users_lock = Mutex.new
users_lock.synchronize do
  users << new_user
end

Array Operations

idx = users.index { |u| u.id == id }
if idx
  users[idx] = updated
end

Kemal Routing

get "/api/users/:id" do |env|
  id = env.params.url["id"]
  env.response.content_type = "application/json"
end

Crystal Unique Features

  • Ruby Syntax: Familiar syntax with compile-time safety
  • Compiled: Native code generation with LLVM
  • Performance: C/C++ speed with Ruby expressiveness
  • Type Safety: Compile-time error detection
  • Macros: Powerful code generation at compile time
  • Zero Overhead: No runtime type system overhead
  • Concurrency: Lightweight fibers for async programming
  • Interop: Direct C library integration
  • Fast Compilation: Quick iteration cycle
  • Nil Safety: Compile-time nil checking

Performance Characteristics

  • Execution Speed: Native compilation, comparable to C
  • Memory: Minimal overhead, efficient allocation
  • Compilation: Fast compilation with LLVM optimization
  • Concurrency: Lightweight fibers with minimal context switching
  • Binary Size: Reasonably small compiled binaries
  • Startup Time: Instant program initialization

Crystal Programming Model

Crystal emphasizes:

  • Expressiveness: Ruby-like syntax for clarity
  • Performance: Compiled efficiency without sacrifice
  • Safety: Type checking prevents bugs at compile time
  • Simplicity: Familiar Ruby syntax for developers
  • Pragmatism: Practical features for real systems
  • Concurrency: Easy async programming with fibers
  • Clarity: Code readability through type inference
  • Speed: Both compilation and execution performance

Comparison with Ruby

Crystal improves on Ruby:

  • Performance: 100x+ faster through compilation
  • Type Safety: Compile-time type checking
  • Memory: Deterministic memory management
  • Startup: No interpreter overhead
  • Concurrency: Fiber-based concurrency model
  • Binary Size: Small standalone executables
  • Deployment: Single binary distribution
  • Type System: Catches errors before runtime

When to Use Crystal

Best for:

  • High-performance web services and APIs
  • Command-line tools and utilities
  • Systems programming with type safety
  • Data processing and ETL pipelines
  • Real-time applications
  • Microservices and distributed systems
  • IoT and embedded applications
  • DevOps and infrastructure automation

Libraries and Frameworks Used

Kemal

  • Lightweight web framework
  • Sinatra-like routing DSL
  • Middleware support
  • Built on Kemal's performance

JSON

  • Built-in JSON serialization
  • JSON.mapping macro
  • Type-safe encoding/decoding

Mutex

  • Thread-safe synchronization
  • Standard library primitive
  • Shared state protection

Core Concepts

Type Inference

  • Deduces types from usage
  • Compile-time safety
  • Minimal annotations needed

JSON Mapping

  • Macro-based serialization
  • Type-safe at compile time
  • Automatic getter/setter generation

Mutex Synchronization

  • Protects shared state
  • synchronize block for safety
  • Prevents data races

Fiber Concurrency

  • Lightweight green threads
  • Efficient I/O handling
  • Channel communication

Macros

  • Compile-time code generation
  • Metaprogramming capabilities
  • DSL creation support

Dependencies

Core platform:

  • Crystal Language: Compiler and runtime
  • LLVM: Optimization and code generation
  • Shards: Package manager
  • Kemal: Web framework
  • Standard Library: Built-in JSON and utilities

This project demonstrates Crystal's exceptional balance of expressiveness, performance, and safety through Ruby-like syntax, static typing, and native code compilation.

Repository

portfolio-project-153-crystal

Owner
Statistic
  • 0
  • 0
  • 0
  • 0
  • 1
  • about 4 hours ago
  • June 13, 2026
License

Links
Synced at

Sat, 13 Jun 2026 10:08:52 GMT

Languages