convez.ai
PluginDesenvolvimento WebAvançado
nanotaboada

RESTful API com Rust e Rocket

nanotaboada/rust-samples-rocket-restful

API RESTful em Rust com Rocket, arquitetura em camadas e SQLite

Ver no GitHub
BomPluginScore · de 0 a 100

Projeto de referência implementando uma API RESTful completa em Rust usando o framework Rocket, com arquitetura em camadas, pool de conexões SQLite via r2d2, e testes de integração abrangentes. Demonstra boas práticas para APIs testáveis e manuteníveis com type safety e estado thread-safe.

Instalação

$npx convez-ai nanotaboada/rust-samples-rocket-restful

1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.

Métricas

Estrelas
0
Forks
3
Acompanhando
1
Saúde
85%
Último commit
há 2 dias
Versão
v1.1.2-drogba
Issues abertas
8
Contribuidores
2

Casos de uso

  • Aprender padrões de arquitetura em Rust para web
  • Estudar testes de integração em APIs RESTful
  • Containerizar e fazer deploy de serviços Rust com Docker

Veredito

Referência técnica sólida com layered architecture, type safety e pipeline CI/CD bem estruturado. Ideal para quem quer aprender Rust em produção, mas exige familiaridade com o ecossistema.

README

A tradução para o português deste README ainda está na fila.

🧪 RESTful API with Rust and Rocket

Rust CI Rust CD CodeQL Advanced codecov License: MIT Dependabot Copilot Claude CodeRabbit

Proof of Concept for a RESTful Web Service built with Rocket and Rust 2024 Edition. This project demonstrates best practices for building a layered, testable, and maintainable API implementing CRUD operations for a Players resource (Argentina 2022 FIFA World Cup squad).

Features

  • 🏗️ Layered Architecture - Modular design with routes, services, repositories, state, and models as distinct packages
  • 🔒 Thread-Safe State - SQLite access via r2d2 connection pool using Rocket's State<T>
  • ✅ Type Safety - Strong Rust type system with Serde for request/response serialization
  • 🚦 Comprehensive Testing - Integration tests covering all endpoints with real SQLite
  • 🐳 Containerized Deployment - Multi-stage Docker builds with migration-based database initialization
  • 🔄 Automated Pipeline - Continuous integration with cargo test, clippy, and GitHub releases

Tech Stack

CategoryTechnology
LanguageRust 2024 Edition
Web FrameworkRocket 0.5.1
SerializationSerde
Unique IDsuuid
ORM / MigrationsDiesel (SQLite + r2d2 features) + diesel_migrations
ContainerizationDocker & Docker Compose

Architecture

Layered architecture with Rocket's managed state for thread-safe dependency sharing.

%%{init: {
  "theme": "default",
  "themeVariables": {
    "fontFamily": "Fira Code, Consolas, monospace",
    "textColor": "#555",
    "lineColor": "#555",
    "lineWidth": 2,
    "clusterBkg": "#f5f5f5",
    "clusterBorder": "#999"
  }
}}%%

graph RL

    tests[tests]

    main[main]
    routes[routes]
    Rocket[Rocket]

    services[services]

    repositories[repositories]
    Diesel[Diesel]

    state[state]
    Serde[Serde]

    models[models]

    %% Dependencies

    routes --> main
    Rocket --> main

    services --> routes
    state --> routes
    Rocket --> routes

    repositories --> services

    state --> repositories
    Diesel --> repositories

    Serde --> models

    %% Soft dependencies

    models -.-> routes
    models -.-> services
    models -.-> repositories

    main -.-> tests

    %% Styling
    classDef core fill:#b3d9ff,stroke:#6db1ff,stroke-width:2px,color:#555,font-family:monospace;
    classDef deps fill:#ffcccc,stroke:#ff8f8f,stroke-width:2px,color:#555,font-family:monospace;
    classDef test fill:#ccffcc,stroke:#53c45e,stroke-width:2px,color:#555,font-family:monospace;

    class main,routes,services,repositories,state,models core
    class Rocket,Serde,Diesel deps
    class tests test

Arrows follow the injection direction (A → B means A is injected into B). Solid = runtime dependency, dotted = structural. Blue = core domain, red = third-party, green = tests.

API Reference

MethodEndpointDescriptionStatus
GET/playersList all players200 OK
GET/players/:idGet player by ID200 OK
GET/players/squadnumber/:squadnumberGet player by squad number200 OK
POST/playersCreate new player201 Created
PUT/players/squadnumber/:squadnumberUpdate player by squad number204 No Content
DELETE/players/squadnumber/:squadnumberRemove player by squad number204 No Content
GET/healthHealth check200 OK

Error codes: 404 Not Found (player not found) · 409 Conflict (duplicate squad number on POST)

Alternatively, use rest/players.rest with the REST Client extension for VS Code, or the built-in HTTP Client in JetBrains IDEs.

Prerequisites

Before you begin, ensure you have the following installed:

  • Rust 2024 Edition or higher (managed via rust-toolchain.toml)
  • Cargo (comes with Rust)
  • Docker & Docker Compose (optional, for containerized deployment)

Quick Start

Clone

git clone https://github.com/nanotaboada/rust-samples-rocket-restful.git
cd rust-samples-rocket-restful

Build

cargo build

Run

cargo run

Access

Once the application is running, you can access:

  • API Server: http://localhost:9000
  • Health Check: http://localhost:9000/health
  • Swagger UI: http://localhost:9000/swagger-ui/

Containers

Build and Start

docker compose up

💡 Note: On first run, the app automatically runs pending Diesel migrations — creating the schema and seeding the full 26-player squad — and stores the database in a persistent volume. On subsequent runs, migrations are skipped and existing data is preserved.

Stop

docker compose down

Reset Database

To remove the volume and let migrations reinitialize the database from scratch on next start:

docker compose down -v

Pull Docker Images

Each release publishes multiple tags for flexibility:

# By semantic version (recommended for production)
docker pull ghcr.io/nanotaboada/rust-samples-rocket-restful:1.0.0

# By nominee name (memorable alternative)
docker pull ghcr.io/nanotaboada/rust-samples-rocket-restful:benzema

# Latest release
docker pull ghcr.io/nanotaboada/rust-samples-rocket-restful:latest

Environment Variables

# Database storage path
# Container default (set in Dockerfile): /storage/players-sqlite3.db
# Local dev fallback (no env var set):   storage/players-sqlite3.db
STORAGE_PATH=/storage/players-sqlite3.db

# Rocket profile: debug or release (default: debug)
ROCKET_PROFILE=release

Contributing

Contributions are welcome! Please see CONTRIBUTING.md for details on:

  • Code of Conduct
  • Development workflow and best practices
  • Commit message conventions (Conventional Commits)
  • Pull request process and requirements

Key guidelines:

  • Follow Conventional Commits for commit messages
  • Run cargo fmt and cargo clippy before committing
  • Ensure all tests pass (cargo test)
  • Keep changes small and focused
  • Review .github/copilot-instructions.md for architectural patterns

Testing:

Run the test suite with Rust's built-in test framework:

# Run all tests
cargo test

# Run tests with output
cargo test -- --nocapture

Command Summary

CommandDescription
cargo runStart development server
cargo buildBuild the application
cargo build --releaseBuild optimized release version
cargo testRun all tests
cargo fmtFormat code
cargo clippyRun linter
cargo cleanClean build artifacts
docker compose buildBuild Docker image
docker compose upStart Docker container
docker compose downStop Docker container
docker compose down -vStop and remove Docker volume
AI Commands
/pre-commitRuns linting, tests, and quality checks before committing
/pre-releasePrepares a release: bumps version, updates CHANGELOG, and opens a PR

Legal

This project is provided for educational and demonstration purposes and may be used in production at your own discretion. All trademarks, service marks, product names, company names, and logos referenced herein are the property of their respective owners and are used solely for identification or illustrative purposes.

Ver o original no GitHub

Bom para

Relacionados