Tutorial

Build a complete, working Azu application from scratch. This comprehensive tutorial will walk you through creating a user management API with type-safe endpoints, validation, real-time features, and a web interface.

What You'll Build

By the end of this tutorial, you'll have a fully functional application with:

  • Type-safe API endpoints for user management (CRUD operations)

  • Request validation with detailed error messages

  • Real-time notifications via WebSocket

  • Template rendering with hot reloading

  • Comprehensive error handling

  • Web interface for user interaction

  • RESTful API design following best practices

Project Setup

1. Create Project Structure

# Create project directory
mkdir user-manager
cd user-manager

# Initialize Crystal project
crystal init app user_manager
cd user_manager

2. Add Dependencies

Edit shard.yml:

Install dependencies:

3. Create Project Structure

Building the Application

Step 1: Define the User Model

Create src/models/user.cr:

Step 2: Create Request Contracts

Create src/requests/create_user_request.cr:

Create src/requests/update_user_request.cr:

Step 3: Create Response Objects

Create src/responses/user_response.cr:

Create src/responses/users_list_response.cr:

Step 4: Create Endpoints

Create src/endpoints/create_user_endpoint.cr:

Create src/endpoints/list_users_endpoint.cr:

Create src/endpoints/show_user_endpoint.cr:

Create src/endpoints/update_user_endpoint.cr:

Create src/endpoints/delete_user_endpoint.cr:

Step 5: Create WebSocket Channel

Create src/channels/user_notification_channel.cr:

Step 6: Create Templates

Create templates/users/index.html:

Step 7: Create Main Application

Create src/user_manager.cr:

Running Your Application

1. Start the Server

You should see:

2. Test the API

Create a User

Response:

List Users

Response:

Get a Specific User

Update a User

Delete a User

3. Test the Web Interface

Open your browser and navigate to http://localhost:4000. You'll see:

  • A form to create new users

  • A list of all users

  • Real-time notifications when users are created, updated, or deleted

4. Test WebSocket Notifications

Open the browser console and watch for real-time notifications when you:

  • Create a new user via the form

  • Delete a user via the API

  • Update a user via the API

Testing Error Handling

Test Validation Errors

Response:

Test Duplicate Email

Test Not Found

Project Structure

Your completed project should look like:

Key Concepts You've Learned

Endpoints

  • Type Safety: Every endpoint defines exactly what it accepts and returns

  • HTTP Methods: Support for GET, POST, PUT, DELETE and more

  • Route Parameters: Access to URL parameters like :id

  • Request Context: Access to headers, query parameters, and more

Request Contracts

  • Validation: Automatic validation using the Schema library

  • Type Safety: Compile-time guarantees for request data

  • Error Messages: Clear, actionable validation errors

  • Flexibility: Support for optional and required fields

Response Objects

  • Structured Output: Consistent JSON responses

  • Status Codes: Proper HTTP status code handling

  • Error Handling: Comprehensive error responses

  • Serialization: Automatic JSON serialization

WebSocket Channels

  • Real-time Communication: Bidirectional communication with clients

  • Event Broadcasting: Notify all connected clients of changes

  • Connection Management: Handle connections and disconnections

  • Message Handling: Process incoming messages from clients

Templates

  • Hot Reload: Automatic template reloading in development

  • Variable Interpolation: Pass data to templates

  • Static Assets: Serve CSS, JavaScript, and other assets

  • HTML Generation: Server-side HTML rendering

Next Steps

Congratulations! You've built a complete Azu application. Here's what to explore next:

  1. Architecture Overview - Understand how Azu works under the hood

  2. Endpoints Deep Dive - Master endpoint patterns and best practices

  3. Request Contracts - Advanced validation techniques

  4. Response Objects - Structured response handling

  5. Real-time Features - Advanced WebSocket patterns

  6. Templates - Template engine and markup DSL

  7. Testing - Write comprehensive tests for your application

Extending Your Application

Consider adding these features:

  • Database Integration: Replace in-memory storage with PostgreSQL or MySQL

  • Authentication: Add user authentication and authorization

  • File Uploads: Handle user avatar uploads

  • Pagination: Add pagination to the users list

  • Search and Filtering: Implement search and filter capabilities

  • Email Notifications: Send emails when users are created

  • API Rate Limiting: Implement rate limiting for API endpoints

  • Request Logging: Add comprehensive request logging and monitoring

  • Caching: Implement caching for better performance

  • Background Jobs: Add background job processing

Production Considerations

When deploying to production:

  1. Environment Variables: Use environment variables for configuration

  2. Database: Set up a proper database (PostgreSQL recommended)

  3. Logging: Configure proper logging levels and outputs

  4. Monitoring: Set up application monitoring and alerting

  5. Security: Implement proper security measures

  6. Performance: Optimize for production workloads

  7. Scaling: Plan for horizontal scaling if needed


Your first complete Azu application is ready! You now have a solid foundation for building more complex applications with type safety, real-time features, and excellent developer experience. 🚀

Last updated

Was this helpful?