Crystal combines Ruby-like syntax with compiled language performance, producing statically-typed, memory-safe binaries that rival C in speed. The Kemal framework brings Sinatra-style simplicity to Crystal. This guide covers building and deploying Crystal web applications on a VPS.
Installing Crystal
# Ubuntu/Debian
curl -fsSL https://crystal-lang.org/install.sh | sudo bash
# Or manual installation
sudo apt install crystal
# Verify
crystal --version
Project Setup
# Create project
crystal init app myapp
cd myapp
# shard.yml (Crystal package manager)
dependencies:
kemal:
github: kemalcr/kemal
pg:
github: will/crystal-pg
db:
github: crystal-lang/crystal-db
json:
github: crystal-lang/json
# Install dependencies
shards install
Application Code
# src/myapp.cr
require "kemal"
require "json"
require "db"
require "pg"
# Database connection
DB_URL = ENV.fetch("DATABASE_URL", "postgres://localhost/myapp_dev")
DATABASE = DB.open(DB_URL)
# Models
class User
include JSON::Serializable
property id : Int32
property name : String
property email : String
def initialize(@id, @name, @email); end
end
# Routes
get "/health" do |env|
env.response.content_type = "application/json"
{status: "healthy"}.to_json
end
get "/api/users" do |env|
env.response.content_type = "application/json"
users = [] of User
DATABASE.query("SELECT id, name, email FROM users") do |rs|
rs.each do
users