{"id":31846892,"url":"https://github.com/sancruz-dev/dotnet-api-vehicle-management","last_synced_at":"2026-05-15T18:33:27.858Z","repository":{"id":311216692,"uuid":"1042916333","full_name":"sancruz-dev/dotnet-api-vehicle-management","owner":"sancruz-dev","description":"A comprehensive RESTful API built with .NET that demonstrates modern software development practices including Clean Architecture, Entity Framework, JWT authentication, and comprehensive testing.","archived":false,"fork":false,"pushed_at":"2025-10-08T09:59:40.000Z","size":336,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-10-19T08:50:31.776Z","etag":null,"topics":["api-rest","clean-architecture","clean-code","dotnet","entity-framework","jwt","linq","mstest","mysql-server","swagger-api"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/sancruz-dev.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-08-22T19:47:40.000Z","updated_at":"2025-10-08T09:59:44.000Z","dependencies_parsed_at":"2025-08-22T22:07:47.242Z","dependency_job_id":null,"html_url":"https://github.com/sancruz-dev/dotnet-api-vehicle-management","commit_stats":null,"previous_names":["sancruz-dev/dotnet-api-vehicle-management"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/sancruz-dev/dotnet-api-vehicle-management","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sancruz-dev%2Fdotnet-api-vehicle-management","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sancruz-dev%2Fdotnet-api-vehicle-management/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sancruz-dev%2Fdotnet-api-vehicle-management/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sancruz-dev%2Fdotnet-api-vehicle-management/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sancruz-dev","download_url":"https://codeload.github.com/sancruz-dev/dotnet-api-vehicle-management/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sancruz-dev%2Fdotnet-api-vehicle-management/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33074844,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-15T11:35:32.926Z","status":"ssl_error","status_checked_at":"2026-05-15T11:35:31.362Z","response_time":103,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api-rest","clean-architecture","clean-code","dotnet","entity-framework","jwt","linq","mstest","mysql-server","swagger-api"],"created_at":"2025-10-12T09:17:35.700Z","updated_at":"2026-05-15T18:33:27.852Z","avatar_url":"https://github.com/sancruz-dev.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Vehicle Management System API\n\n[![.NET](https://img.shields.io/badge/.NET-7.0-blue.svg)](https://dotnet.microsoft.com/)\n[![Entity Framework](https://img.shields.io/badge/Entity%20Framework-512BD4?style=flat\u0026logo=.net\u0026logoColor=white)](https://docs.microsoft.com/en-us/ef/)\n[![MySQL](https://img.shields.io/badge/MySQL-4479A1?style=flat\u0026logo=mysql\u0026logoColor=white)](https://www.mysql.com/)\n[![JWT](https://img.shields.io/badge/JWT-000000?style=flat\u0026logo=json-web-tokens\u0026logoColor=white)](https://jwt.io/)\n[![Swagger](https://img.shields.io/badge/Swagger-85EA2D?style=flat\u0026logo=swagger\u0026logoColor=black)](https://swagger.io/)\n[![MSTest](https://img.shields.io/badge/MSTest-68217A?style=flat\u0026logo=microsoft\u0026logoColor=white)](https://docs.microsoft.com/en-us/dotnet/core/testing/unit-testing-with-mstest)\n\nA comprehensive RESTful API built with .NET that demonstrates modern software development practices including Clean Architecture, Entity Framework, JWT authentication, and comprehensive testing.\n\n## 🚀 Features\n\n- **Vehicle CRUD Operations**: Complete Create, Read, Update, Delete functionality for vehicle management\n- **User Authentication \u0026 Authorization**: JWT-based authentication with role-based access control\n- **Admin Management**: Dedicated endpoints for administrator operations\n- **Data Validation**: Robust server-side validation with custom validation rules\n- **API Documentation**: Interactive Swagger/OpenAPI documentation\n- **Memory Caching**: Optimized performance with in-memory caching strategies\n- **Comprehensive Testing**: Unit tests with MSTest framework ensuring code reliability\n\n## 🏗️ Architecture \u0026 Design Patterns\n\nThis project follows **Clean Architecture** principles with clear separation of concerns:\n\n```\ndotnet-api-vehicle-management/\n│\n├── API/                        # Projeto principal (API Minimalista)\n│   ├── Domain/                 # Núcleo do domínio (coração do DDD)\n│   │   ├── Entities/           # Entidades de negócio\n│   │   ├── Enums/              # Enumerações específicas do domínio\n│   │   ├── ValueObjects/       # Objetos de valor (imutáveis, com igualdade por valor)\n│   │   ├── Interfaces/         # Contratos de repositórios e serviços\n│   │   └── Services/           # Regras de domínio e políticas de negócio\n│   │\n│   ├── Infrastructure/         # Implementações concretas do domínio\n│   │   ├── DB/                 # Contexto, mapeamentos e migrações\n│   │   ├── Auth/               # Implementação de autenticação/autorização\n│   │   └── Repositories/       # Repositórios concretos das interfaces de domínio\n│   │\n│   ├── Controllers/            # Pontos de entrada (endpoints da Minimal API)\n│   ├── ModelViews/             # Modelos de entrada e saída (DTOs, Responses)\n│   ├── Program.cs              # Inicialização da API\n│   ├── Startup.cs              # Configuração de serviços e middlewares\n│   └── appsettings.json\n│\n└── Test/                       # Projeto de testes\n    ├── Domain/                 # Testes de regras de negócio\n    ├── Mocks/                  # Simulações (repositórios, serviços)\n    ├── Helpers/                # Utilitários de teste\n    └── Requests/               # Cenários e casos de teste\n\n```\n\n### Key Architectural Decisions:\n- **Clean Code**: Following SOLID principles and clean coding practices\n- **Repository Pattern**: Abstraction layer for data access operations\n- **Dependency Injection**: Loose coupling between components\n- **Entity Framework Core**: Code-first approach with migrations\n- **JWT Authentication**: Stateless authentication mechanism\n\n## 🛠️ Technologies \u0026 Tools\n\n### Backend Framework\n- **.NET 6+**: Modern cross-platform framework\n- **ASP.NET Core Web API**: RESTful API development\n- **Entity Framework Core**: Object-relational mapping (ORM)\n\n### Database\n- **MySQL**: Relational database management\n- **MySQL CLI**: Database operations and management\n\n### Authentication \u0026 Security\n- **JWT (JSON Web Tokens)**: Secure authentication\n- **Role-based Authorization**: Admin and user access levels\n- **Password Hashing**: Secure password storage\n\n### Testing\n- **MSTest**: Unit testing framework\n- **Test-Driven Development**: Ensuring code reliability and maintainability\n\n### Documentation \u0026 Tools\n- **Swagger/OpenAPI**: Interactive API documentation\n- **Postman Collections**: API testing and validation\n\n## 📋 API Endpoints\n\n### Authentication\n```http\nPOST /api/auth/login          # User authentication\nPOST /api/auth/register       # User registration\n```\n\n### Vehicle Management\n```http\nGET    /api/vehicles          # Get all vehicles\nGET    /api/vehicles/{id}     # Get vehicle by ID\nPOST   /api/vehicles          # Create new vehicle\nPUT    /api/vehicles/{id}     # Update vehicle\nDELETE /api/vehicles/{id}     # Delete vehicle\n```\n\n### Administration\n```http\nGET    /api/admin/users       # Get all users (Admin only)\nPOST   /api/admin/seed        # Seed default administrator\nPUT    /api/admin/users/{id}  # Update user (Admin only)\n```\n\n---\n\n## 🔐 Roles \u0026 Permissions\n\nThis API uses **role-based access control (RBAC)** with two profiles:\n\n| Role | Description | Access Level |\n|------|-------------|--------------|\n| `Adm` | Full administrator | All endpoints, including admin-only operations |\n| `Editor` | Limited user | Can read and create vehicles, but cannot update/delete or manage admins |\n\nThe following endpoints require the `Adm` role specifically:\n\n- `POST /Admins/admin` — Register a new admin\n- `GET /Admins/admins` — List all admins\n- `GET /Admins/admins/{id}` — Get admin by ID\n- `PUT /Veiculos/veiculo/{id}` — Update a vehicle\n- `DELETE /Veiculos/veiculo/{id}` — Delete a vehicle\n\n\u003e ⚠️ **Important:** All endpoints (except `POST /Admins/login`) require a valid JWT token. Make sure you have at least one user registered in the database before testing.\n\nA default `Adm` user is seeded automatically via migrations:\n\n```\nEmail: admin@teste.com\nPassword: 123456\nRole: Adm\n```\n\n---\n\n## 🔑 Authenticating via Swagger (Step-by-Step)\n\nAll protected routes require a Bearer token. Follow these steps to authenticate directly in the Swagger UI:\n\n### Step 1 — Run the application and open Swagger\n\nStart the API and navigate to:\n\n```\nhttp://localhost:5097/swagger\n```\n\nor, if using HTTPS:\n\n```\nhttps://localhost:7044/swagger\n```\n\n### Step 2 — Call the login endpoint\n\n1. In the Swagger UI, locate and expand the **`POST /Admins/login`** endpoint.\n2. Click **\"Try it out\"**.\n3. Fill in the request body with valid credentials. Example using the seeded admin:\n\n```json\n{\n  \"email\": \"admin@teste.com\",\n  \"senha\": \"123456\"\n}\n```\n\n4. Click **\"Execute\"**.\n\n### Step 3 — Copy the JWT token\n\nIn the response body (HTTP 200), you will receive a JSON object similar to:\n\n```json\n{\n  \"email\": \"admin@teste.com\",\n  \"perfil\": \"Adm\",\n  \"token\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...\"\n}\n```\n\nCopy the full value of the `\"token\"` field.\n\n### Step 4 — Authorize in Swagger\n\n1. Click the **\"Authorize 🔓\"** button at the top right of the Swagger UI page.\n2. In the input field labeled **\"Value\"**, type:\n\n```\nBearer \u003cpaste your token here\u003e\n```\n\nExample:\n\n```\nBearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...\n```\n\n3. Click **\"Authorize\"**, then **\"Close\"**.\n\n\u003e The lock icon on each endpoint will now appear closed (🔒), indicating you are authenticated.\n\n### Step 5 — Use the protected endpoints\n\nYou can now call any endpoint. Keep in mind:\n\n- Endpoints marked with `[Authorize]` will work with any valid token.\n- Endpoints marked with `[Authorize(Roles = \"Adm\")]` require your logged-in user to have the `Adm` profile. If you log in as an `Editor`, these endpoints will return **HTTP 403 Forbidden**.\n\n### Token Expiration\n\nTokens are valid for **24 hours**. If you receive a `401 Unauthorized` after some time, repeat Steps 2–4 to generate a new token.\n\n---\n\n## 🔧 Getting Started\n\n### Prerequisites\n- .NET 7+ SDK\n- MySQL Server\n- MySQL CLI tools\n\n### Installation\n\n1. **Clone the repository**\n```bash\ngit clone [repository-url]\ncd dotnet-api-vehicle-management\n```\n\n2. **Configure Database Connection**\n\nEdit `API/appsettings.json` with your MySQL credentials:\n\n```json\n{\n  \"ConnectionStrings\": {\n    \"MySql\": \"Server=localhost;Database=db_minimal_api;Uid=your_username;Pwd=your_password;\"\n  },\n  \"Jwt\": {\n    \"Key\": \"minimal-api-alunos-vamos_la\"\n  }\n}\n```\n\n3. **Apply Database Migrations**\n```bash\ncd API\ndotnet ef database update\n```\n\nThis will create the database schema and automatically seed the default `Adm` user (`admin@teste.com` / `123456`).\n\n4. **Run the Application**\n```bash\ndotnet run\n```\n\n5. **Access Swagger Documentation**\n\nNavigate to `http://localhost:5097/swagger` and follow the [authentication steps above](#-authenticating-via-swagger-step-by-step) to start using the API.\n\n## 🧪 Testing\n\nRun the comprehensive test suite:\n\n```bash\ndotnet test\n```\n\n### Test Coverage\n- **Unit Tests**: Core business logic validation\n- **Integration Tests**: API endpoint testing\n- **Persistence Tests**: Database operations verification\n- **Authentication Tests**: JWT and authorization testing\n\n## 🔒 Security Features\n\n- **JWT Authentication**: Secure token-based authentication\n- **Password Security**: BCrypt password hashing\n- **Role-based Access Control**: Different permission levels\n- **Input Validation**: Protection against malicious inputs\n- **HTTPS Enforcement**: Secure data transmission\n\n## 📊 Performance Optimizations\n\n- **In-Memory Caching**: Frequently accessed data caching\n- **Efficient Queries**: Optimized Entity Framework queries\n- **Asynchronous Operations**: Non-blocking I/O operations\n- **Connection Pooling**: Database connection optimization\n\n## 🏆 Best Practices Implemented\n\n- **Clean Architecture**: Maintainable and testable code structure\n- **SOLID Principles**: Object-oriented design principles\n- **Repository Pattern**: Data access abstraction\n- **Dependency Injection**: Loose coupling and testability\n- **Configuration Management**: Environment-specific settings\n- **Error Handling**: Centralized exception management\n\n## 🤝 Contributing\n\n1. Fork the repository\n2. Create a feature branch (`git checkout -b feature/amazing-feature`)\n3. Commit your changes (`git commit -m 'Add amazing feature'`)\n4. Push to the branch (`git push origin feature/amazing-feature`)\n5. Open a Pull Request\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsancruz-dev%2Fdotnet-api-vehicle-management","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsancruz-dev%2Fdotnet-api-vehicle-management","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsancruz-dev%2Fdotnet-api-vehicle-management/lists"}