An open API service indexing awesome lists of open source software.

https://github.com/sancruz-dev/dotnet-api-vehicle-management

A comprehensive RESTful API built with .NET that demonstrates modern software development practices including Clean Architecture, Entity Framework, JWT authentication, and comprehensive testing.
https://github.com/sancruz-dev/dotnet-api-vehicle-management

api-rest clean-architecture clean-code dotnet entity-framework jwt linq mstest mysql-server swagger-api

Last synced: about 2 months ago
JSON representation

A comprehensive RESTful API built with .NET that demonstrates modern software development practices including Clean Architecture, Entity Framework, JWT authentication, and comprehensive testing.

Awesome Lists containing this project

README

          

# Vehicle Management System API

[![.NET](https://img.shields.io/badge/.NET-7.0-blue.svg)](https://dotnet.microsoft.com/)
[![Entity Framework](https://img.shields.io/badge/Entity%20Framework-512BD4?style=flat&logo=.net&logoColor=white)](https://docs.microsoft.com/en-us/ef/)
[![MySQL](https://img.shields.io/badge/MySQL-4479A1?style=flat&logo=mysql&logoColor=white)](https://www.mysql.com/)
[![JWT](https://img.shields.io/badge/JWT-000000?style=flat&logo=json-web-tokens&logoColor=white)](https://jwt.io/)
[![Swagger](https://img.shields.io/badge/Swagger-85EA2D?style=flat&logo=swagger&logoColor=black)](https://swagger.io/)
[![MSTest](https://img.shields.io/badge/MSTest-68217A?style=flat&logo=microsoft&logoColor=white)](https://docs.microsoft.com/en-us/dotnet/core/testing/unit-testing-with-mstest)

A comprehensive RESTful API built with .NET that demonstrates modern software development practices including Clean Architecture, Entity Framework, JWT authentication, and comprehensive testing.

## 🚀 Features

- **Vehicle CRUD Operations**: Complete Create, Read, Update, Delete functionality for vehicle management
- **User Authentication & Authorization**: JWT-based authentication with role-based access control
- **Admin Management**: Dedicated endpoints for administrator operations
- **Data Validation**: Robust server-side validation with custom validation rules
- **API Documentation**: Interactive Swagger/OpenAPI documentation
- **Memory Caching**: Optimized performance with in-memory caching strategies
- **Comprehensive Testing**: Unit tests with MSTest framework ensuring code reliability

## 🏗️ Architecture & Design Patterns

This project follows **Clean Architecture** principles with clear separation of concerns:

```
dotnet-api-vehicle-management/

├── API/ # Projeto principal (API Minimalista)
│ ├── Domain/ # Núcleo do domínio (coração do DDD)
│ │ ├── Entities/ # Entidades de negócio
│ │ ├── Enums/ # Enumerações específicas do domínio
│ │ ├── ValueObjects/ # Objetos de valor (imutáveis, com igualdade por valor)
│ │ ├── Interfaces/ # Contratos de repositórios e serviços
│ │ └── Services/ # Regras de domínio e políticas de negócio
│ │
│ ├── Infrastructure/ # Implementações concretas do domínio
│ │ ├── DB/ # Contexto, mapeamentos e migrações
│ │ ├── Auth/ # Implementação de autenticação/autorização
│ │ └── Repositories/ # Repositórios concretos das interfaces de domínio
│ │
│ ├── Controllers/ # Pontos de entrada (endpoints da Minimal API)
│ ├── ModelViews/ # Modelos de entrada e saída (DTOs, Responses)
│ ├── Program.cs # Inicialização da API
│ ├── Startup.cs # Configuração de serviços e middlewares
│ └── appsettings.json

└── Test/ # Projeto de testes
├── Domain/ # Testes de regras de negócio
├── Mocks/ # Simulações (repositórios, serviços)
├── Helpers/ # Utilitários de teste
└── Requests/ # Cenários e casos de teste

```

### Key Architectural Decisions:
- **Clean Code**: Following SOLID principles and clean coding practices
- **Repository Pattern**: Abstraction layer for data access operations
- **Dependency Injection**: Loose coupling between components
- **Entity Framework Core**: Code-first approach with migrations
- **JWT Authentication**: Stateless authentication mechanism

## 🛠️ Technologies & Tools

### Backend Framework
- **.NET 6+**: Modern cross-platform framework
- **ASP.NET Core Web API**: RESTful API development
- **Entity Framework Core**: Object-relational mapping (ORM)

### Database
- **MySQL**: Relational database management
- **MySQL CLI**: Database operations and management

### Authentication & Security
- **JWT (JSON Web Tokens)**: Secure authentication
- **Role-based Authorization**: Admin and user access levels
- **Password Hashing**: Secure password storage

### Testing
- **MSTest**: Unit testing framework
- **Test-Driven Development**: Ensuring code reliability and maintainability

### Documentation & Tools
- **Swagger/OpenAPI**: Interactive API documentation
- **Postman Collections**: API testing and validation

## 📋 API Endpoints

### Authentication
```http
POST /api/auth/login # User authentication
POST /api/auth/register # User registration
```

### Vehicle Management
```http
GET /api/vehicles # Get all vehicles
GET /api/vehicles/{id} # Get vehicle by ID
POST /api/vehicles # Create new vehicle
PUT /api/vehicles/{id} # Update vehicle
DELETE /api/vehicles/{id} # Delete vehicle
```

### Administration
```http
GET /api/admin/users # Get all users (Admin only)
POST /api/admin/seed # Seed default administrator
PUT /api/admin/users/{id} # Update user (Admin only)
```

---

## 🔐 Roles & Permissions

This API uses **role-based access control (RBAC)** with two profiles:

| Role | Description | Access Level |
|------|-------------|--------------|
| `Adm` | Full administrator | All endpoints, including admin-only operations |
| `Editor` | Limited user | Can read and create vehicles, but cannot update/delete or manage admins |

The following endpoints require the `Adm` role specifically:

- `POST /Admins/admin` — Register a new admin
- `GET /Admins/admins` — List all admins
- `GET /Admins/admins/{id}` — Get admin by ID
- `PUT /Veiculos/veiculo/{id}` — Update a vehicle
- `DELETE /Veiculos/veiculo/{id}` — Delete a vehicle

> ⚠️ **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.

A default `Adm` user is seeded automatically via migrations:

```
Email: admin@teste.com
Password: 123456
Role: Adm
```

---

## 🔑 Authenticating via Swagger (Step-by-Step)

All protected routes require a Bearer token. Follow these steps to authenticate directly in the Swagger UI:

### Step 1 — Run the application and open Swagger

Start the API and navigate to:

```
http://localhost:5097/swagger
```

or, if using HTTPS:

```
https://localhost:7044/swagger
```

### Step 2 — Call the login endpoint

1. In the Swagger UI, locate and expand the **`POST /Admins/login`** endpoint.
2. Click **"Try it out"**.
3. Fill in the request body with valid credentials. Example using the seeded admin:

```json
{
"email": "admin@teste.com",
"senha": "123456"
}
```

4. Click **"Execute"**.

### Step 3 — Copy the JWT token

In the response body (HTTP 200), you will receive a JSON object similar to:

```json
{
"email": "admin@teste.com",
"perfil": "Adm",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
```

Copy the full value of the `"token"` field.

### Step 4 — Authorize in Swagger

1. Click the **"Authorize 🔓"** button at the top right of the Swagger UI page.
2. In the input field labeled **"Value"**, type:

```
Bearer
```

Example:

```
Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
```

3. Click **"Authorize"**, then **"Close"**.

> The lock icon on each endpoint will now appear closed (🔒), indicating you are authenticated.

### Step 5 — Use the protected endpoints

You can now call any endpoint. Keep in mind:

- Endpoints marked with `[Authorize]` will work with any valid token.
- 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**.

### Token Expiration

Tokens are valid for **24 hours**. If you receive a `401 Unauthorized` after some time, repeat Steps 2–4 to generate a new token.

---

## 🔧 Getting Started

### Prerequisites
- .NET 7+ SDK
- MySQL Server
- MySQL CLI tools

### Installation

1. **Clone the repository**
```bash
git clone [repository-url]
cd dotnet-api-vehicle-management
```

2. **Configure Database Connection**

Edit `API/appsettings.json` with your MySQL credentials:

```json
{
"ConnectionStrings": {
"MySql": "Server=localhost;Database=db_minimal_api;Uid=your_username;Pwd=your_password;"
},
"Jwt": {
"Key": "minimal-api-alunos-vamos_la"
}
}
```

3. **Apply Database Migrations**
```bash
cd API
dotnet ef database update
```

This will create the database schema and automatically seed the default `Adm` user (`admin@teste.com` / `123456`).

4. **Run the Application**
```bash
dotnet run
```

5. **Access Swagger Documentation**

Navigate to `http://localhost:5097/swagger` and follow the [authentication steps above](#-authenticating-via-swagger-step-by-step) to start using the API.

## 🧪 Testing

Run the comprehensive test suite:

```bash
dotnet test
```

### Test Coverage
- **Unit Tests**: Core business logic validation
- **Integration Tests**: API endpoint testing
- **Persistence Tests**: Database operations verification
- **Authentication Tests**: JWT and authorization testing

## 🔒 Security Features

- **JWT Authentication**: Secure token-based authentication
- **Password Security**: BCrypt password hashing
- **Role-based Access Control**: Different permission levels
- **Input Validation**: Protection against malicious inputs
- **HTTPS Enforcement**: Secure data transmission

## 📊 Performance Optimizations

- **In-Memory Caching**: Frequently accessed data caching
- **Efficient Queries**: Optimized Entity Framework queries
- **Asynchronous Operations**: Non-blocking I/O operations
- **Connection Pooling**: Database connection optimization

## 🏆 Best Practices Implemented

- **Clean Architecture**: Maintainable and testable code structure
- **SOLID Principles**: Object-oriented design principles
- **Repository Pattern**: Data access abstraction
- **Dependency Injection**: Loose coupling and testability
- **Configuration Management**: Environment-specific settings
- **Error Handling**: Centralized exception management

## 🤝 Contributing

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request