Skip to content

Abiola26/Bookstore

Repository files navigation

πŸ“š Bookstore API - Production-Ready Implementation

A comprehensive, enterprise-level Online Bookstore REST API built with .NET 10, SQL Server, and Clean Architecture principles.

Build Status License .NET Version

🌟 Features

βœ… Complete Feature Set

  • Book Management: CRUD operations, search, filtering, pagination
  • Category Management: Organize books into categories
  • User Authentication: JWT-based with secure password hashing (BCrypt)
  • Role-Based Authorization: Admin and User roles
  • Order Management: Create orders, track status, cancel orders
  • Inventory Management: Stock management with transaction safety
  • Global Exception Handling: Centralized error responses
  • API Documentation: Interactive Swagger/OpenAPI
  • Soft Delete: Logical deletion with audit trail

πŸ—οΈ Architecture

  • Clean Architecture: Domain, Application, Infrastructure, API layers
  • Repository Pattern: Abstraction over data access
  • Unit of Work: Transaction management
  • Service Layer: Business logic orchestration
  • DTOs: Data Transfer Objects for API contracts
  • Value Objects: ISBN and Money as domain-driven design values

πŸ”’ Security

  • JWT Authentication: Stateless, token-based authentication
  • Password Security: BCrypt hashing with adaptive work factor
  • SQL Injection Prevention: Parameterized queries via EF Core
  • HTTPS: Enforced in production
  • CORS: Configurable cross-origin policies
  • Role-Based Access Control: Fine-grained authorization

πŸ“Š Data

  • SQL Server: Robust relational database
  • Entity Framework Core: Code-First ORM
  • Migrations: Version-controlled schema changes
  • Soft Delete: Logical deletion support
  • Optimistic Concurrency: RowVersion for conflict detection
  • Comprehensive Indexing: Performance optimization

πŸš€ Performance

  • Pagination: Efficient data retrieval
  • Eager Loading: N+1 query prevention
  • Indexing Strategy: Optimized database queries
  • Connection Pooling: Efficient resource management
  • Async/Await: Non-blocking I/O operations
  • Caching Ready: Designed for Redis integration

πŸ“‹ Project Structure

Bookstore/
β”œβ”€β”€ Bookstore.Domain/               # Domain entities & value objects
β”‚   β”œβ”€β”€ Entities/
β”‚   β”‚   β”œβ”€β”€ BaseEntity.cs          # Base class with audit fields
β”‚   β”‚   β”œβ”€β”€ Book.cs
β”‚   β”‚   β”œβ”€β”€ Category.cs
β”‚   β”‚   β”œβ”€β”€ User.cs
β”‚   β”‚   β”œβ”€β”€ Order.cs
β”‚   β”‚   └── OrderItem.cs
β”‚   └── ValueObjects/
β”‚       β”œβ”€β”€ ISBN.cs
β”‚       └── Money.cs
β”‚
β”œβ”€β”€ Bookstore.Application/          # Application services & DTOs
β”‚   β”œβ”€β”€ DTOs/
β”‚   β”‚   β”œβ”€β”€ BookDtos.cs
β”‚   β”‚   β”œβ”€β”€ CategoryDtos.cs
β”‚   β”‚   β”œβ”€β”€ UserDtos.cs
β”‚   β”‚   └── OrderDtos.cs
β”‚   β”œβ”€β”€ Services/
β”‚   β”‚   └── IServices.cs
β”‚   β”œβ”€β”€ Repositories/
β”‚   β”‚   └── IRepositories.cs
β”‚   β”œβ”€β”€ Validators/
β”‚   β”‚   └── DtoValidators.cs
β”‚   β”œβ”€β”€ Exceptions/
β”‚   β”‚   └── CustomExceptions.cs
β”‚   └── Common/
β”‚       └── ApiResponse.cs
β”‚
β”œβ”€β”€ Bookstore.Infrastructure/       # EF Core, repositories, services
β”‚   β”œβ”€β”€ Persistence/
β”‚   β”‚   β”œβ”€β”€ BookStoreDbContext.cs
β”‚   β”‚   β”œβ”€β”€ Configurations/
β”‚   β”‚   └── Repositories/
β”‚   β”œβ”€β”€ Services/
β”‚   β”‚   β”œβ”€β”€ AuthenticationService.cs
β”‚   β”‚   β”œβ”€β”€ BookService.cs
β”‚   β”‚   β”œβ”€β”€ CategoryService.cs
β”‚   β”‚   └── OrderService.cs
β”‚   β”œβ”€β”€ Middleware/
β”‚   β”‚   └── GlobalExceptionMiddleware.cs
β”‚   └── DependencyInjection.cs
β”‚
β”œβ”€β”€ Bookstore.API/                  # ASP.NET Core API
β”‚   β”œβ”€β”€ Controllers/
β”‚   β”‚   β”œβ”€β”€ AuthController.cs
β”‚   β”‚   β”œβ”€β”€ BooksController.cs
β”‚   β”‚   β”œβ”€β”€ CategoriesController.cs
β”‚   β”‚   └── OrdersController.cs
β”‚   β”œβ”€β”€ Program.cs
β”‚   └── appsettings.json
β”‚
β”œβ”€β”€ docs/                           # Project documentation
β”‚   β”œβ”€β”€ api/
β”‚   β”‚   └── POSTMAN_COLLECTION.json # API testing collection
β”‚   β”œβ”€β”€ history/                    # Historical records & reviews
β”‚   β”‚   β”œβ”€β”€ CODE_REVIEW_SENIOR_ENGINEER.md
β”‚   β”‚   └── TEST_FAILURES_ANALYSIS_AND_FIXES.md
β”‚   β”œβ”€β”€ summaries/                  # Feature and logic summaries
β”‚   β”‚   └── SHOPPING_CART_FEATURE_SUMMARY.md
β”‚   β”œβ”€β”€ BEST_PRACTICES.md           # Implementation best practices
β”‚   β”œβ”€β”€ DATABASE_MIGRATIONS.md       # Migration guide
β”‚   β”œβ”€β”€ DEPLOYMENT_CHECKLIST.md      # Deployment guide
β”‚   β”œβ”€β”€ NUGET_PACKAGES.md           # Required NuGet packages
β”‚   β”œβ”€β”€ TESTING_GUIDE.md            # Testing strategies
β”‚   └── PROJECT_SPECIFICATION.md     # Core project requirements
└── .editorconfig                   # Code style & cleanup rules

πŸš€ Quick Start

Prerequisites

  • .NET 10 SDK
  • SQL Server (or SQL Server Express)
  • Visual Studio 2026 (or VS Code)

1. Clone & Setup

# Clone repository
git clone https://github.com/your-org/bookstore-api.git
cd bookstore-api

# Restore packages
dotnet restore

2. Configure Database

Edit Bookstore.API/appsettings.json:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(local)\\SQLEXPRESS;Database=BookstoreDb;Trusted_Connection=true;"
  },
  "JWT": {
    "Key": "your-secure-key-minimum-32-characters-xxx",
    "Issuer": "BookstoreAPI",
    "Audience": "BookstoreClients"
  }
}

3. Create Database

Option A: Using Package Manager Console

Add-Migration InitialCreate
Update-Database

Option B: Using .NET CLI

cd Bookstore.Infrastructure
dotnet ef migrations add InitialCreate
dotnet ef database update

4. Run Application

cd Bookstore.API
dotnet run

# Application starts at: https://localhost:5001
# Swagger UI: https://localhost:5001/swagger/index.html

πŸ“– API Documentation

Authentication

# Register
POST /api/auth/register
Content-Type: application/json

{
  "fullName": "John Doe",
  "email": "john@example.com",
  "password": "SecurePassword123",
  "phoneNumber": "+1234567890"
}

# Login
POST /api/auth/login
{
  "email": "john@example.com",
  "password": "SecurePassword123"
}

# Response
{
  "success": true,
  "data": {
    "userId": "guid",
    "fullName": "John Doe",
    "email": "john@example.com",
    "role": "User",
    "token": "eyJhbGciOiJIUzI1NiIs...",
    "expiresAt": "2025-01-09T12:00:00Z"
  },
  "statusCode": 200
}

Books

# Get all books (paginated)
GET /api/books?pageNumber=1&pageSize=10

# Get book by ID
GET /api/books/{id}

# Search books
GET /api/books/search/gatsby

# Get books by category
GET /api/books/category/{categoryId}?pageNumber=1&pageSize=10

# Create book (Admin only)
POST /api/books
Authorization: Bearer {admin-token}

# Update book (Admin only)
PUT /api/books/{id}

# Delete book (Admin only)
DELETE /api/books/{id}

Categories

# Get all categories
GET /api/categories

# Get category by ID
GET /api/categories/{id}

# Create category (Admin)
POST /api/categories

# Update category (Admin)
PUT /api/categories/{id}

# Delete category (Admin)
DELETE /api/categories/{id}

Orders

# Create order
POST /api/orders
Authorization: Bearer {user-token}

# Get order by ID
GET /api/orders/{id}

# Get user's orders
GET /api/orders/my-orders?pageNumber=1&pageSize=10

# Update order status (Admin)
PUT /api/orders/{id}/status

# Cancel order
DELETE /api/orders/{id}/cancel

πŸ§ͺ Testing

Postman Collection

Import POSTMAN_COLLECTION.json into Postman for API testing.

Setup Variables:

  • base_url: https://localhost:5001
  • access_token: Token from login response
  • admin_token: Admin user's token
  • category_id, book_id, order_id: IDs from responses

Unit Testing

# Run tests
dotnet test

# With coverage
dotnet test /p:CollectCoverage=true /p:CoverageFormat=opencover

πŸ“Š Database Schema

Tables

  • Users: Registered users with authentication
  • Categories: Book categories
  • Books: Book inventory with stock management
  • Orders: Customer orders
  • OrderItems: Individual items in orders

Key Features

  • βœ… Referential integrity with foreign keys
  • βœ… Unique constraints (ISBN, Email, Category Name)
  • βœ… Soft delete with IsDeleted flag
  • βœ… Audit fields (CreatedAt, UpdatedAt, CreatedBy, UpdatedBy)
  • βœ… Optimistic concurrency with RowVersion
  • βœ… Strategic indexing for performance

πŸ”’ Security Features

Authentication

  • JWT tokens with 24-hour expiration
  • Email and password validation
  • Secure password hashing (BCrypt)

Authorization

  • Role-based access control
  • Admin-only operations protected
  • User resources isolated

Data Protection

  • SQL injection prevention (parameterized queries)
  • XSS protection (no inline scripts)
  • CORS policy enforcement
  • HTTPS enforced

Audit Trail

  • CreatedBy, UpdatedBy tracking
  • CreatedAt, UpdatedAt timestamps
  • Soft delete for data recovery

πŸ“ˆ Performance Metrics

  • API Response Time: < 2 seconds (target)
  • Database Queries: < 500ms (P95)
  • Pagination: 10-100 items per page
  • Concurrent Users: 1000+ (with proper scaling)
  • Order Processing: < 1 second

πŸ› οΈ Troubleshooting

Build Errors

NuGet Restore Failed

dotnet nuget locals all --clear
dotnet restore

Missing Assembly References

# Verify packages installed
dotnet list package

Runtime Errors

Connection String Issues

  • Verify SQL Server is running
  • Check connection string in appsettings.json
  • Ensure database exists or let EF Core create it

Migration Failures

  • Check for pending migrations: dotnet ef migrations list
  • Roll back if needed: dotnet ef database update <PreviousMigration>

Authentication Issues

  • Verify JWT Key is set in appsettings.json
  • Check token hasn't expired
  • Ensure token is in Authorization header: Bearer {token}

πŸ“š Additional Documentation


πŸ”„ CI/CD Pipeline

GitHub Actions Example

name: Build & Test

on: [push, pull_request]

jobs:
  build:
    runs-on: ubuntu-latest
    
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-dotnet@v1
        with:
          dotnet-version: '10.0.0'
      
      - run: dotnet restore
      - run: dotnet build
      - run: dotnet test

πŸ“‹ Deployment Checklist

  • Database backups configured
  • Connection strings updated (no hardcoded values)
  • JWT keys rotated and secured in Key Vault
  • HTTPS certificate installed
  • Logging configured (structured logging)
  • Monitoring and alerting set up
  • Load balancer configured
  • Cache layer deployed (if using Redis)
  • Firewall rules configured
  • Database replicas set up

🀝 Contributing

  1. Create feature branch: git checkout -b feature/my-feature
  2. Commit changes: git commit -am 'Add my feature'
  3. Push to branch: git push origin feature/my-feature
  4. Submit pull request

Code Style

  • Follow C# naming conventions
  • Use async/await for I/O operations
  • Add XML documentation for public APIs
  • Write unit tests for new features

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


πŸ™‹ Support

For issues, questions, or suggestions:

  • Open an issue on GitHub
  • Check existing documentation
  • Review troubleshooting guide

πŸŽ‰ What's Included

βœ… Backend API: Full REST API implementation βœ… Database: SQL Server with EF Core migrations βœ… Authentication: JWT with role-based authorization βœ… Error Handling: Global exception middleware βœ… Logging: Structured logging throughout βœ… Documentation: Comprehensive guides and API docs βœ… Testing: Postman collection for API testing βœ… Security: BCrypt passwords, SQL injection prevention βœ… Performance: Pagination, indexing, lazy loading βœ… Production Ready: Best practices implemented


πŸ“ž Contact

Project Lead: Abdulmuheez Ogunrinde Email: abdulmuheezabiola@gmail.com GitHub: Abiola26


πŸ™ Acknowledgments

  • Microsoft Entity Framework Core team
  • ASP.NET Core community
  • Security best practices from OWASP

Last Updated: January 2025 Version: 1.0.0
Status: βœ… Production Ready

Bookstore API Architecture


πŸ“Œ Quick Links


Happy coding! πŸš€

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors