This is a boilerplate project for building web APIs in Rust, inspired by Laravel. It provides a structured architecture with authentication, database integration, and Docker support.
- Axum for fast HTTP server
- JWT authentication with bcrypt password hashing
- PostgreSQL with Sqlx for database operations
- Redis for caching/session storage
- Docker setup with Nginx reverse proxy
- Migrations for database schema
- Logging with Tracing
- Modular architecture (controllers, services, repositories, models)
- Install Rust (1.70+) and Cargo.
- Install
cargo-generatefor easy template cloning:cargo install cargo-generate - Generate a new project from this boilerplate:
Replace
cargo generate --git https://github.com/crystaldaking/rust-api-boilerplate.git --name my-api-projectyour-usernamewith your GitHub username. If the repo is public, this will create a local copy.
- Create a
.envfile (copy from.env.exampleif provided):DATABASE_URL=postgres://postgres:password@localhost:5432/my_db REDIS_URL=redis://127.0.0.1:6379 JWT_SECRET=your-secret-key JWT_EXP_MINUTES=60 APP_HOST=0.0.0.0 APP_PORT=8000 - Run migrations:
cargo sqlx migrate run
-
Locally:
- Start Postgres and Redis (e.g., via Docker or locally).
cargo run- API at http://localhost:8000
-
For Development (with hot reload):
- Install dependencies:
make install-deps - Run with auto-restart on code changes:
make dev - API at http://localhost:8000
- Install dependencies:
-
With Docker:
make docker-build- Or manual:
docker-compose up --build - Nginx at http://localhost (port 80), API at http://localhost:8000
make install-deps: Install cargo-watch and sqlx-climake dev: Start development server with auto-reloadmake test: Run testsmake watch-test: Auto-run tests on changesmake migrate: Run database migrationsmake docker-up: Start Docker servicesmake docker-down: Stop Docker servicesmake docker-logs: View API logs
POST /auth/register- Register user:{"email": "[email protected]", "password": "pass"}POST /auth/login- Login:{"email": "[email protected]", "password": "pass"}→ Returns JWT tokenGET /auth/me- Get user info (requiresAuthorization: Bearer <token>)
To add new controllers, models, etc.:
- Add a Model: Create
src/models/new_model.rs, e.g., for posts:#[derive(Debug, Serialize, Deserialize, FromRow)] pub struct Post { id: Uuid, title: String, content: String, user_id: Uuid, created_at: DateTime<Utc> }
- Add Repository:
src/repositories/new_repository.rswith CRUD methods using Sqlx. - Add Service:
src/services/new_service.rsfor business logic. - Add Controller:
src/http/controllers/new.rswith handlers. - Register Controller:
- Add to
src/http/controllers.rs:pub mod new; - In
src/http/routes.rs, add routes:Router::new().route("/new", post(controllers::new::handler)) - If protected, use in
protected_routes()or add new middleware.
- Add to
Add new migrations in migrations/ and run cargo sqlx migrate run.
For tests, add #[cfg(test)] modules.
MIT
- Axum для быстрого HTTP-сервера
- JWT-аутентификация с хэшированием паролей через bcrypt
- PostgreSQL с Sqlx для работы с базой данных
- Redis для кэширования/сессий
- Docker с Nginx reverse proxy
- Миграции для схемы БД
- Логирование с Tracing
- Модульная архитектура (контроллеры, сервисы, репозитории, модели)
- Установите Rust (1.70+) и Cargo.
- Установите
cargo-generateдля клонирования шаблона:cargo install cargo-generate - Сгенерируйте новый проект из этого boilerplate:
Замените
cargo generate --git https://github.com/crystaldaking/rust-api-boilerplate.git --name my-api-projectyour-usernameна ваш GitHub username. Если репо публичное, это создаст локальную копию.
- Создайте
.envфайл (скопируйте из.env.example, если есть):DATABASE_URL=postgres://postgres:password@localhost:5432/my_db REDIS_URL=redis://127.0.0.1:6379 JWT_SECRET=your-secret-key JWT_EXP_MINUTES=60 APP_HOST=0.0.0.0 APP_PORT=8000 - Запустите миграции:
cargo sqlx migrate run
-
Локально:
- Запустите Postgres и Redis (например, через Docker или локально).
cargo run- API на http://localhost:8000
-
Для разработки (с горячей перезагрузкой):
- Установите зависимости:
make install-deps - Запустите с авто-перезапуском при изменениях:
make dev - API на http://localhost:8000
- Установите зависимости:
-
Через Docker:
make docker-build- Или вручную:
docker-compose up --build - Nginx на http://localhost (порт 80), API на http://localhost:8000
make install-deps: Установить cargo-watch и sqlx-climake dev: Запустить сервер разработки с авто-перезагрузкойmake test: Запустить тестыmake watch-test: Авто-запуск тестов при измененияхmake migrate: Запустить миграции БДmake docker-up: Запустить Docker сервисыmake docker-down: Остановить Docker сервисыmake docker-logs: Просмотр логов API
POST /auth/register- Регистрация:{"email": "[email protected]", "password": "pass"}POST /auth/login- Вход:{"email": "[email protected]", "password": "pass"}→ Возвращает JWT токенGET /auth/me- Получить инфо о пользователе (нуженAuthorization: Bearer <token>)
Чтобы добавить новые контроллеры, модели и т.д.:
- Добавить Модель: Создайте
src/models/new_model.rs, например, для постов:#[derive(Debug, Serialize, Deserialize, FromRow)] pub struct Post { id: Uuid, title: String, content: String, user_id: Uuid, created_at: DateTime<Utc> }
- Добавить Репозиторий:
src/repositories/new_repository.rsс CRUD методами через Sqlx. - Добавить Сервис:
src/services/new_service.rsдля бизнес-логики. - Добавить Контроллер:
src/http/controllers/new.rsс обработчиками. - Зарегистрировать Контроллер:
- Добавьте в
src/http/controllers.rs:pub mod new; - В
src/http/routes.rsдобавьте маршруты:Router::new().route("/new", post(controllers::new::handler)) - Если защищено, используйте в
protected_routes()или добавьте новый middleware.
- Добавьте в
Добавьте новые миграции в migrations/ и запустите cargo sqlx migrate run.
Для тестов добавьте модули #[cfg(test)].
MIT