Building a User API

This tutorial walks you through building a complete RESTful API for user management with type-safe endpoints, validation, and proper error handling.

What You'll Build

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

  • CRUD endpoints for user management

  • Request validation with error messages

  • Type-safe request and response contracts

  • Proper error handling and status codes

Prerequisites

Step 1: Project Setup

Create a new project:

crystal init app user_api
cd user_api

Update shard.yml:

Install dependencies:

Create the project structure:

Step 2: Create the User Model

Create src/models/user.cr:

Note: This tutorial uses in-memory storage for simplicity. See Working with Databases for production database integration.

Step 3: Create Request Contracts

Request contracts validate incoming data automatically.

Create src/requests/create_user_request.cr:

Create src/requests/update_user_request.cr:

Step 4: Create Response Objects

Response objects define your API's output format.

Create src/responses/user_response.cr:

Create src/responses/users_list_response.cr:

Step 5: Create Endpoints

Now create the CRUD 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 6: Create the Main Application

Create src/user_api.cr:

Step 7: Run and Test

Start the server:

Create a User

Response:

List Users

Get a User

Update a User

Delete a User

Test Validation

Response:

Key Concepts Learned

Type-Safe Contracts

Every endpoint declares exactly what it accepts and returns:

Automatic Validation

Request contracts validate data before your handler runs:

Structured Error Responses

Validation errors return consistent, structured JSON responses with proper HTTP status codes.

Route Parameters

Access URL segments via the params hash:

Project Structure

Next Steps

You've built a complete REST API. Continue learning with:


Your API is ready! You now understand how to build type-safe, validated REST APIs with Azu.

Last updated

Was this helpful?