How abhimvp/bookly-fastapi works
Project Type and Purpose
• This is a backend RESTful API built with FastAPI (an ASGI framework) that manages books, users, reviews, and tags.
• It uses Pydantic/SQLModel for data validation and ORM, Alembic for migrations, Redis for JWT token revocation, and FastAPI-Mail/SMTP for email.
Main Architectural Components
• API Layer: FastAPI application, routers grouping endpoints by module (auth, books, reviews, tags).
• Business Logic Layer: “service” classes under each module (service.py) implementing CRUD and domain rules.
• Data Layer:
– PostgreSQL (via SQLModel + SQLAlchemy) for persistent storage.
– Alembic for schema migrations (“migrations/” directory and alembic.ini).
– Redis (aioredis) for token revocation/block lists.
• Infrastructure & Config:
– Dependency Injection via FastAPI’s Depends (dependencies.py).
– Configuration management (src/config.py, environment variables).
– Middleware (src/middleware.py) for cross-cutting concerns (logging, CORS, auth checks).
– Error handling (src/errors.py) with custom exception handlers.
• External Services:
– SMTP/email server via FastAPI-Mail (src/mail.py + email templates in src/templates).
– Optional WebSocket support (inherent via ASGI).
Relationships & Data Flow
1. Client (Postman/RESTfox) sends HTTP/HTTPS request.
2. Uvicorn (ASGI server) routes the request into the FastAPI app.
3. Request passes through Middleware (authentication, logging, CORS).
4. Router dispatch: Based on path prefix (e.g., /auth, /books), control flows to the correct module’s routes.py.
5. Route handler extracts/validates input via Pydantic schemas (schemas.py) and dependencies (e.g., DB session).
6. Route calls Service layer (service.py) to perform business logic, which:
a. Interacts with the database via SQLModel models (src/db/models.py) and session (src/db/main.py).
b. May push/revoke tokens in Redis.
c. May call FastAPI-Mail to send emails, signing tokens with ItsDangerous or PyJWT.
7. Service returns domain objects (Pydantic models) back to route, which serializes them to JSON.
8. FastAPI sends the HTTP response back to the client.
Architectural Patterns & Principles
• Layered Architecture: Clear separation of API (routers), Business (services), Data (repositories/ORM).
• Dependency Injection: FastAPI’s Depends to inject DB sessions, security checks, configs.
• Modularization: Each domain (auth, books, reviews, tags) lives in its own package.
• Async/Await End-to-End: ASGI-compatible stack, non-blocking DB calls (asyncpg), Redis calls (aioredis).
• Migrations as Code: Alembic environment configured to auto-generate and apply schema changes.
• Security: JWT Bearer tokens, role-based access control (RBAC), token revocation, password hashing.