Skip to content

shankmaha/multi-module-spring-boot-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Multi-Module Spring Boot REST API

A comprehensive Spring Boot application with multiple modules featuring REST APIs, Microsoft Graph API integration, Webhook support, document processing, and environment-based API documentation control.

πŸ“‹ Table of Contents

✨ Features

Core Features

  • βœ… Multi-Module Architecture: 3 service modules (User, Order, Payment) + Common module
  • βœ… Centralized API Documentation: Swagger/OpenAPI with token-based security
  • βœ… Environment-Based Documentation Control:
    • UAT: Documentation ENABLED and secured
    • PROD: Documentation DISABLED for security
  • βœ… Custom Business Response Wrapper: Consistent API response format
  • βœ… Token-Based Authentication: JWT authentication for all endpoints
  • βœ… Global Exception Handling: Centralized error handling

Module-Specific Features

User Service

  1. REST APIs: Standard CRUD operations for users
  2. Document Management:
    • Upload documents (bills, invoices, receipts)
    • Generate PDF invoices
    • Email generated documents to clients
  3. Microsoft Graph API Integration:
    • User profile management
    • Send emails
    • Access calendar and OneDrive
  4. Webhook Support:
    • Register webhooks
    • Receive and process webhook events
    • Validate webhook signatures
    • Event history tracking

πŸ—οΈ Architecture

multi-module-api/
β”œβ”€β”€ common/                    # Shared utilities and configurations
β”‚   β”œβ”€β”€ response/             # ApiResponse wrapper
β”‚   β”œβ”€β”€ exception/            # Global exception handlers
β”‚   β”œβ”€β”€ security/             # JWT utilities
β”‚   └── config/               # Swagger configuration
β”œβ”€β”€ user-service/             # User management + Document + Graph + Webhook
β”‚   β”œβ”€β”€ controller/
β”‚   β”œβ”€β”€ service/
β”‚   β”œβ”€β”€ dto/
β”‚   └── resources/
β”œβ”€β”€ order-service/            # Order management (to be implemented)
└── payment-service/          # Payment processing (to be implemented)

πŸ“¦ Prerequisites

  • Java: JDK 17 or 21
  • Maven: 3.6+
  • IntelliJ IDEA: 2023+ (Community or Ultimate)
  • Optional: Microsoft Azure account (for Graph API)
  • Optional: SMTP server credentials (for email functionality)

πŸ“ Project Structure

multi-module-api/
β”œβ”€β”€ pom.xml                           # Root POM with dependency management
β”œβ”€β”€ common/
β”‚   β”œβ”€β”€ pom.xml
β”‚   └── src/main/java/com/example/common/
β”‚       β”œβ”€β”€ response/ApiResponse.java
β”‚       β”œβ”€β”€ exception/
β”‚       β”‚   β”œβ”€β”€ GlobalExceptionHandler.java
β”‚       β”‚   β”œβ”€β”€ BusinessException.java
β”‚       β”‚   β”œβ”€β”€ ResourceNotFoundException.java
β”‚       β”‚   └── UnauthorizedException.java
β”‚       β”œβ”€β”€ security/JwtTokenUtil.java
β”‚       └── config/SwaggerConfig.java
β”œβ”€β”€ user-service/
β”‚   β”œβ”€β”€ pom.xml
β”‚   └── src/main/
β”‚       β”œβ”€β”€ java/com/example/userservice/
β”‚       β”‚   β”œβ”€β”€ UserServiceApplication.java
β”‚       β”‚   β”œβ”€β”€ controller/
β”‚       β”‚   β”‚   β”œβ”€β”€ AuthController.java
β”‚       β”‚   β”‚   β”œβ”€β”€ UserController.java
β”‚       β”‚   β”‚   β”œβ”€β”€ DocumentController.java
β”‚       β”‚   β”‚   β”œβ”€β”€ GraphApiController.java
β”‚       β”‚   β”‚   └── WebhookController.java
β”‚       β”‚   β”œβ”€β”€ service/
β”‚       β”‚   β”‚   β”œβ”€β”€ UserService.java
β”‚       β”‚   β”‚   β”œβ”€β”€ DocumentService.java
β”‚       β”‚   β”‚   β”œβ”€β”€ GraphApiService.java
β”‚       β”‚   β”‚   └── WebhookService.java
β”‚       β”‚   └── dto/
β”‚       β”‚       β”œβ”€β”€ UserDto.java
β”‚       β”‚       β”œβ”€β”€ InvoiceDto.java
β”‚       β”‚       β”œβ”€β”€ DocumentMetadataDto.java
β”‚       β”‚       β”œβ”€β”€ WebhookRegistrationDto.java
β”‚       β”‚       β”œβ”€β”€ WebhookPayloadDto.java
β”‚       β”‚       β”œβ”€β”€ GraphUserDto.java
β”‚       β”‚       └── EmailMessageDto.java
β”‚       └── resources/
β”‚           β”œβ”€β”€ application.yml
β”‚           β”œβ”€β”€ application-uat.yml
β”‚           └── application-prod.yml
β”œβ”€β”€ order-service/
β”‚   └── pom.xml
└── payment-service/
    └── pom.xml

πŸš€ IntelliJ IDEA Setup

Step 1: Import Project

  1. Open IntelliJ IDEA
  2. Select File β†’ Open
  3. Navigate to the multi-module-api folder
  4. Click Open
  5. IntelliJ will detect Maven project and import automatically

Step 2: Configure Project SDK

  1. Go to File β†’ Project Structure
  2. Under Project Settings β†’ Project
  3. Set SDK to Java 17 or 21
  4. Set Language Level to 17 or 21
  5. Click Apply and OK

Step 3: Enable Annotation Processing (for Lombok)

  1. Go to File β†’ Settings (Windows/Linux) or IntelliJ IDEA β†’ Preferences (Mac)
  2. Navigate to Build, Execution, Deployment β†’ Compiler β†’ Annotation Processors
  3. Check Enable annotation processing
  4. Click Apply and OK

Step 4: Install Lombok Plugin (if not already installed)

  1. Go to File β†’ Settings β†’ Plugins
  2. Search for "Lombok"
  3. Install the Lombok plugin
  4. Restart IntelliJ IDEA

Step 5: Maven Build

  1. Open Maven panel (View β†’ Tool Windows β†’ Maven)
  2. Expand multi-module-api
  3. Run Lifecycle β†’ clean
  4. Run Lifecycle β†’ install

βš™οΈ Configuration

1. Environment Profiles

The application supports three profiles:

Default (Development)

# No profile specified - uses application.yml

UAT (Swagger ENABLED)

java -jar -Dspring.profiles.active=uat user-service.jar
  • βœ… Swagger UI: ENABLED
  • βœ… Token authentication: REQUIRED
  • βœ… Public access: YES (with token)

Production (Swagger DISABLED)

java -jar -Dspring.profiles.active=prod user-service.jar
  • ❌ Swagger UI: DISABLED
  • ❌ API documentation: NOT ACCESSIBLE
  • βœ… Security: MAXIMUM

2. Configure Email (Optional)

Update application.yml:

spring:
  mail:
    host: smtp.gmail.com
    port: 587
    username: your-email@gmail.com
    password: your-app-password  # Use App Password for Gmail
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true

For Gmail:

  1. Enable 2-Factor Authentication
  2. Generate App Password: https://myaccount.google.com/apppasswords
  3. Use the generated password in configuration

3. Configure Microsoft Graph API (Optional)

To enable Graph API features:

  1. Register Application in Azure AD:

    • Go to https://portal.azure.com
    • Navigate to Azure Active Directory β†’ App registrations
    • Click "New registration"
    • Note: Client ID, Tenant ID
  2. Generate Client Secret:

    • In your app registration β†’ Certificates & secrets
    • Create new client secret
    • Copy the secret value
  3. Configure API Permissions:

    • In your app registration β†’ API permissions
    • Add Microsoft Graph permissions:
      • User.Read
      • User.Read.All
      • Mail.Send
      • Calendars.Read
      • Files.Read
    • Grant admin consent
  4. Update Configuration:

microsoft:
  graph:
    client-id: your-client-id
    tenant-id: your-tenant-id
    client-secret: your-client-secret
  1. Uncomment Graph SDK Code:
    • Open GraphApiService.java
    • Uncomment the Graph SDK initialization and API calls

4. JWT Configuration

Update JWT secret (especially for production):

jwt:
  secret: your-very-long-and-secure-secret-key-here
  expiration: 86400000  # 24 hours

🎯 Running the Application

Method 1: IntelliJ IDEA Run Configuration

  1. Open UserServiceApplication.java
  2. Click the green play button next to the class
  3. Or right-click β†’ Run 'UserServiceApplication'

To run with specific profile:

  1. Click Run β†’ Edit Configurations
  2. Select your run configuration
  3. In VM options, add: -Dspring.profiles.active=uat or -Dspring.profiles.active=prod
  4. Click Apply and OK
  5. Run the configuration

Method 2: Maven Command

# Default profile (development)
cd user-service
mvn spring-boot:run

# UAT profile (Swagger enabled)
mvn spring-boot:run -Dspring-boot.run.profiles=uat

# Production profile (Swagger disabled)
mvn spring-boot:run -Dspring-boot.run.profiles=prod

Method 3: Build and Run JAR

# Build
cd multi-module-api
mvn clean package

# Run with specific profile
java -jar user-service/target/user-service-1.0.0.jar --spring.profiles.active=uat

πŸ“š API Documentation

Accessing Swagger UI

UAT Environment (ENABLED):

  1. Start application with UAT profile: -Dspring.profiles.active=uat
  2. Open browser: http://localhost:8080/swagger-ui.html
  3. You'll see grouped API documentation for all modules

Production Environment (DISABLED):

  • Swagger is completely disabled
  • Attempting to access /swagger-ui.html will return 404
  • This is intentional for security

API Groups in Swagger

The documentation is organized into groups:

  1. 0-authentication: Login and token generation
  2. 1-user-service: User CRUD operations
  3. 2-order-service: Order management (placeholder)
  4. 3-payment-service: Payment processing (placeholder)
  5. 4-webhooks: Webhook registration and events
  6. 5-graph-api: Microsoft Graph integrations
  7. all-apis: Combined view of all endpoints

Authenticating in Swagger

  1. Get Token:

    • Open Swagger UI
    • Go to 0-authentication group
    • Expand POST /api/auth/login
    • Click Try it out
    • Use credentials:
      {
        "username": "admin",
        "password": "admin123"
      }
    • Click Execute
    • Copy the accessToken from response
  2. Authorize:

    • Click the Authorize button (lock icon) at top right
    • Paste the token in the Value field
    • Click Authorize
    • Click Close
  3. Test APIs:

    • Now you can test any API endpoint
    • The token will be automatically included in requests

πŸ§ͺ Testing the APIs

1. Authentication

# Get JWT Token
curl -X POST http://localhost:8080/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "username": "admin",
    "password": "admin123"
  }'

Response:

{
  "success": true,
  "message": "Login successful",
  "data": {
    "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "tokenType": "Bearer",
    "expiresAt": 1704067200000,
    "username": "admin"
  },
  "timestamp": "2024-01-15T10:30:00"
}

2. User Management

# Create User
curl -X POST http://localhost:8080/api/user \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "firstName": "John",
    "lastName": "Doe",
    "email": "john.doe@example.com",
    "phone": "+1234567890"
  }'

# Get All Users
curl -X GET http://localhost:8080/api/user \
  -H "Authorization: Bearer YOUR_TOKEN"

# Get User by ID
curl -X GET http://localhost:8080/api/user/1 \
  -H "Authorization: Bearer YOUR_TOKEN"

3. Document Upload

# Upload Document
curl -X POST http://localhost:8080/api/document/upload \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -F "file=@/path/to/your/document.pdf" \
  -F "documentType=BILL" \
  -F "notes=January utility bill"

4. Generate Invoice

# Generate Invoice PDF
curl -X POST http://localhost:8080/api/document/generate/invoice \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "invoiceNumber": "INV-2024-001",
    "invoiceDate": "2024-01-15",
    "dueDate": "2024-02-15",
    "sellerName": "ABC Corporation",
    "sellerAddress": "123 Business St, City, Country",
    "sellerEmail": "billing@abccorp.com",
    "customerName": "John Doe",
    "customerEmail": "john.doe@example.com",
    "items": [
      {
        "description": "Consulting Services",
        "quantity": 10,
        "unitPrice": 100.00,
        "unit": "hours",
        "lineTotal": 1000.00
      }
    ],
    "subtotal": 1000.00,
    "taxRate": 10.0,
    "taxAmount": 100.00,
    "totalAmount": 1100.00,
    "currency": "USD",
    "notes": "Thank you for your business!"
  }' \
  --output invoice.pdf

5. Register Webhook

# Register Webhook
curl -X POST http://localhost:8080/api/webhook/register \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://your-server.com/webhook/receiver",
    "events": ["user.created", "user.updated", "order.completed"],
    "name": "My Webhook",
    "description": "Receives user and order events"
  }'

6. Send Webhook Event

# Send Event to Webhook (simulating external system)
curl -X POST http://localhost:8080/api/webhook/events/webhook-12345 \
  -H "Content-Type: application/json" \
  -H "X-Webhook-Signature: YOUR_SIGNATURE" \
  -d '{
    "event_type": "user.created",
    "user_id": "123",
    "timestamp": "2024-01-15T10:30:00Z",
    "data": {
      "email": "newuser@example.com",
      "name": "New User"
    }
  }'

πŸ“¦ Module Details

Common Module

  • ApiResponse: Standard response wrapper
  • GlobalExceptionHandler: Centralized exception handling
  • JwtTokenUtil: JWT token generation and validation
  • SwaggerConfig: API documentation configuration
  • Custom Exceptions: BusinessException, ResourceNotFoundException, UnauthorizedException

User Service

  • User Management: CRUD operations
  • Document Upload: Multi-part file upload
  • Invoice Generation: PDF creation with iText
  • Email Service: Send generated documents
  • Microsoft Graph API: Office 365 integration
  • Webhook Support: Event-driven architecture

Order Service (Placeholder)

  • To be implemented with similar structure
  • Suggested endpoints:
    • POST /api/order - Create order
    • GET /api/order/{id} - Get order
    • PUT /api/order/{id} - Update order
    • GET /api/order - List orders

Payment Service (Placeholder)

  • To be implemented with similar structure
  • Suggested endpoints:
    • POST /api/payment - Process payment
    • GET /api/payment/{id} - Get payment status
    • POST /api/payment/refund - Refund payment

πŸ”’ Security Features

  1. JWT Authentication: All APIs (except login) require valid JWT token
  2. Token-Based Swagger Access: Swagger UI requires authentication in UAT
  3. Environment-Based Controls: Documentation disabled in production
  4. Webhook Signature Validation: HMAC-SHA256 signature verification
  5. Input Validation: Jakarta validation on all DTOs
  6. CORS Configuration: Can be configured per environment

πŸ“ Important Notes

For Production Deployment

  1. Disable Swagger: Ensure spring.profiles.active=prod
  2. Use Strong JWT Secret: At least 64 characters
  3. Configure SSL: Enable HTTPS
  4. Use Environment Variables: Don't hardcode secrets
  5. Configure Proper SMTP: Use production mail server
  6. Set Up Monitoring: Use Spring Boot Actuator
  7. Database Integration: Replace in-memory storage with actual database

Swagger Documentation Control

# UAT - Swagger ENABLED
springdoc:
  api-docs:
    enabled: true
  swagger-ui:
    enabled: true

# PROD - Swagger DISABLED
springdoc:
  api-docs:
    enabled: false
  swagger-ui:
    enabled: false

Default Credentials

Login Credentials (Change in production):

  • Username: admin
  • Password: admin123

πŸ› οΈ Troubleshooting

Issue: Lombok not working

Solution: Enable annotation processing in IntelliJ (see Step 3 in IntelliJ Setup)

Issue: Cannot access Swagger UI

Solution:

  • Check if running with correct profile
  • UAT profile: Swagger is enabled
  • PROD profile: Swagger is disabled (intended behavior)

Issue: File upload fails

Solution: Check spring.servlet.multipart.max-file-size configuration

Issue: Email sending fails

Solution:

  • Verify SMTP credentials
  • For Gmail, use App Password instead of regular password
  • Check firewall settings

Issue: Graph API calls fail

Solution:

  • Verify Azure AD app registration
  • Check API permissions are granted
  • Uncomment Graph SDK code in GraphApiService.java
  • Verify credentials in application.yml

πŸ“„ License

This project is created for demonstration purposes.

πŸ‘₯ Support

For issues or questions:

  1. Check this README
  2. Review application logs
  3. Check Swagger documentation (in UAT environment)

Created with ❀️ for demonstrating Spring Boot best practices

About

Production-ready multi-module Spring Boot 3.x REST API with JWT authentication

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages