Working with Databases

This tutorial teaches you how to connect Azu to a database using CQL, Crystal's type-safe ORM.

What You'll Build

By the end of this tutorial, you'll have:

  • CQL connected to PostgreSQL (or SQLite for development)

  • Type-safe database models

  • CRUD operations with proper validation

  • Integration with Azu endpoints

Prerequisites

Step 1: Add CQL Dependencies

Update your shard.yml:

name: user_api
version: 0.1.0

dependencies:
  azu:
    github: azutoolkit/azu
    version: ~> 0.5.28
  cql:
    github: azutoolkit/cql
    version: ~> 0.1.0
  # Choose your database driver:
  pg:                           # PostgreSQL
    github: will/crystal-pg
  # OR
  # sqlite3:                    # SQLite (development)
  #   github: crystal-lang/crystal-sqlite3

crystal: >= 0.35.0
license: MIT

Install dependencies:

Step 2: Define the Schema

Create src/config/database.cr:

For SQLite development:

Step 3: Create the Database

For PostgreSQL:

For SQLite:

Step 4: Create the Model

Replace src/models/user.cr with a CQL-backed model:

Step 5: Update Endpoints

Update src/endpoints/create_user_endpoint.cr:

Update src/endpoints/list_users_endpoint.cr:

Update src/endpoints/show_user_endpoint.cr:

Update src/endpoints/update_user_endpoint.cr:

Update src/endpoints/delete_user_endpoint.cr:

Step 6: Update Main Application

Update src/user_api.cr:

Step 7: Adding Relationships

Add a posts table to your schema:

Create src/models/post.cr:

Update the User model with the relationship:

Step 8: Query Examples

Environment Configuration

Create a .env file for development:

For production:

Key Concepts Learned

Schema Definition

Model Definition

CRUD Operations

Next Steps

Your API now persists data to a database. Continue learning with:


Database integration complete! Your application now stores data persistently with type-safe queries.

Last updated

Was this helpful?