# API Documentation ## Overview This document provides comprehensive API documentation for this workspace. It includes endpoint definitions, request/response formats, usage examples, and testing guidelines designed for AI Models to understand, design, modify, and implement the API. ## API Meta Data ### Base URLs | Environment | URL | Description | |-------------|-----|-------------| | **Development** | `http://localhost:3000/api` | Local development server | | **Staging** | `https://staging-api.example.com/api` | Pre-production testing environment | | **Production** | `https://api.example.com/api` | Live production environment | ### API Version - **Current Version**: v1.0.0 - **Versioning Strategy**: URL-based versioning (`/api/v1/endpoint`) - **Supported Versions**: v1.0.x (latest) ### Authentication All protected endpoints require JWT authentication: ```http Authorization: Bearer ``` ### Rate Limiting | Level | Limit | Description | |-------|-------|-------------| | **Standard** | 100 requests/15 minutes | Per IP address | | **Authenticated** | 1000 requests/15 minutes | Per authenticated user | ### Common Headers | Header | Required | Description | Example | |--------|----------|-------------|---------| | `Content-Type` | Yes | Request content type | `application/json` | | `Accept` | Yes | Expected response type | `application/json` | | `Authorization` | Conditional | JWT bearer token | `Bearer eyJhbGciOiJIUzI1NiIs...` | | `X-Request-ID` | Optional | Unique request identifier | `req_123456` | ### Common Error Response Format ```json { "error": { "code": "ERROR_CODE", "message": "Human readable message", "details": {} }, "timestamp": "2024-01-15T10:30:00Z", "requestId": "req_123" } ``` ## API Definitions This section is organized by controller classes. Each controller groups related API endpoints. --- ### AuthController **Source Code**: `server/src/main/java/com/example/api/controller/AuthController.java` **Description**: Handles authentication-related operations including login, registration, and token management. | Endpoint | Method | Description | Security | Status Codes | |----------|--------|-------------|----------|--------------| | `/auth/login` | POST | Authenticate user and obtain JWT token | Public | 200, 400, 401, 429, 500 | | `/auth/register` | POST | Register new user account | Public | 201, 400, 409, 429, 500 | | `/auth/refresh` | POST | Refresh JWT token | JWT Required | 200, 401, 500 | | `/auth/logout` | POST | Invalidate current token | JWT Required | 200, 401, 500 | #### POST /auth/login **Description**: Authenticates a user with email and password credentials, returning a JWT token for subsequent API calls. **Request Parameters**: | Parameter | Type | Required | Description | Example | |-----------|------|----------|-------------|---------| | `email` | string | Yes | User's email address | `"user@example.com"` | | `password` | string | Yes | User's password | `"password123"` | **Success Response (200)**: ```json { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "user": { "id": 1, "email": "user@example.com", "name": "John Doe", "roles": ["USER"] }, "expiresIn": 3600 } ``` **Error Responses**: - **400** - Invalid request format - **401** - Invalid credentials - **429** - Rate limit exceeded #### POST /auth/register **Description**: Creates a new user account with email, password, and profile information. **Request Parameters**: | Parameter | Type | Required | Description | Example | |-----------|------|----------|-------------|---------| | `email` | string | Yes | User's email address (must be unique) | `"newuser@example.com"` | | `password` | string | Yes | Password (min 8 chars, 1 uppercase, 1 number) | `"Password123!"` | | `name` | string | Yes | User's full name | `"New User"` | | `confirmPassword` | string | Yes | Password confirmation (must match password) | `"Password123!"` | **Success Response (201)**: ```json { "user": { "id": 2, "email": "newuser@example.com", "name": "New User", "createdAt": "2024-01-15T10:30:00Z" }, "verificationRequired": true } ``` **Error Responses**: - **400** - Validation error (invalid email format, weak password) - **409** - Email already exists - **429** - Rate limit exceeded #### POST /auth/refresh **Description**: Refreshes an existing JWT token before it expires. **Request Parameters**: | Parameter | Type | Required | Description | Example | |-----------|------|----------|-------------|---------| | `refreshToken` | string | Yes | Valid refresh token | `"eyJhbGciOiJIUzI1NiIs..."` | **Success Response (200)**: ```json { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "expiresIn": 3600 } ``` **Error Responses**: - **401** - Invalid or expired refresh token - **500** - Internal server error #### POST /auth/logout **Description**: Invalidates the current JWT token and refresh token. **Request Parameters**: None (uses JWT token from Authorization header) **Success Response (200)**: ```json { "message": "Successfully logged out" } ``` **Error Responses**: - **401** - Invalid or expired token - **500** - Internal server error --- ### UserController **Source Code**: `server/src/main/java/com/example/api/controller/UserController.java` **Description**: Manages user profile operations including viewing and updating user information. | Endpoint | Method | Description | Security | Status Codes | |----------|--------|-------------|----------|--------------| | `/users/me` | GET | Get current authenticated user's profile | JWT Required | 200, 401, 404, 500 | | `/users/me` | PUT | Update current user's profile | JWT Required | 200, 400, 401, 404, 500 | | `/users/{id}` | GET | Get public user profile by ID | Public | 200, 404, 500 | #### GET /users/me **Description**: Retrieves the profile information of the currently authenticated user. **Request Parameters**: None (uses JWT token for identification) **Success Response (200)**: ```json { "id": 1, "email": "user@example.com", "name": "John Doe", "profile": { "avatarUrl": "https://example.com/avatar.jpg", "phoneNumber": "+1234567890", "address": "123 Main St, City, Country" }, "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-15T10:30:00Z" } ``` **Error Responses**: - **401** - Invalid or expired token - **404** - User not found - **500** - Internal server error #### PUT /users/me **Description**: Updates the profile information of the currently authenticated user. Only provided fields will be updated. **Request Parameters**: | Parameter | Type | Required | Description | Example | |-----------|------|----------|-------------|---------| | `name` | string | No | User's full name | `"Updated Name"` | | `profile` | object | No | Profile information object | See below | | `profile.phoneNumber` | string | No | Phone number in E.164 format | `"+0987654321"` | | `profile.address` | string | No | Full address | `"456 Oak St, City, Country"` | | `profile.avatarUrl` | string | No | Profile image URL | `"https://example.com/avatar.jpg"` | **Success Response (200)**: ```json { "id": 1, "email": "user@example.com", "name": "Updated Name", "profile": { "avatarUrl": "https://example.com/avatar.jpg", "phoneNumber": "+0987654321", "address": "456 Oak St, City, Country" }, "updatedAt": "2024-01-20T12:00:00Z" } ``` **Error Responses**: - **400** - Invalid data format - **401** - Invalid or expired token - **404** - User not found #### GET /users/{id} **Description**: Retrieves the public profile information of a user by their ID. **Path Parameters**: | Parameter | Type | Required | Description | Example | |-----------|------|----------|-------------|---------| | `id` | integer | Yes | User ID | `1` | **Success Response (200)**: ```json { "id": 1, "name": "John Doe", "profile": { "avatarUrl": "https://example.com/avatar.jpg" }, "createdAt": "2024-01-01T00:00:00Z" } ``` **Error Responses**: - **404** - User not found - **500** - Internal server error --- ### ProductController **Source Code**: `server/src/main/java/com/example/api/controller/ProductController.java` **Description**: Manages product catalog operations including listing, searching, and product details. | Endpoint | Method | Description | Security | Status Codes | |----------|--------|-------------|----------|--------------| | `/products` | GET | List products with pagination and filters | Public | 200, 400, 500 | | `/products/{id}` | GET | Get product details by ID | Public | 200, 404, 500 | | `/products` | POST | Create a new product | JWT Required (ADMIN) | 201, 400, 401, 403, 409, 500 | | `/products/{id}` | PUT | Update an existing product | JWT Required (ADMIN) | 200, 400, 401, 403, 404, 500 | | `/products/{id}` | DELETE | Delete a product | JWT Required (ADMIN) | 204, 401, 403, 404, 500 | #### GET /products **Description**: Retrieves a paginated list of products with optional filtering and sorting. **Query Parameters**: | Parameter | Type | Required | Description | Example | |-----------|------|----------|-------------|---------| | `page` | integer | No | Page number (default: 1) | `1` | | `limit` | integer | No | Items per page (default: 20, max: 100) | `20` | | `categoryId` | integer | No | Filter by category ID | `5` | | `search` | string | No | Search query for product name/description | `"headphones"` | | `minPrice` | number | No | Minimum price filter | `10.00` | | `maxPrice` | number | No | Maximum price filter | `500.00` | | `sortBy` | string | No | Sort field (price, name, createdAt) | `"price"` | | `sortOrder` | string | No | Sort direction (asc, desc) | `"asc"` | **Success Response (200)**: ```json { "data": [ { "id": 101, "sku": "ELEC-001", "name": "Wireless Bluetooth Headphones", "description": "Noise-cancelling wireless headphones with 30-hour battery", "price": 129.99, "stockQuantity": 50, "categoryId": 5, "images": [ { "url": "https://example.com/products/headphones-1.jpg", "altText": "Front view of headphones", "isPrimary": true, "order": 1 } ] } ], "pagination": { "page": 1, "limit": 20, "total": 150, "totalPages": 8 } } ``` **Error Responses**: - **400** - Invalid query parameters - **500** - Internal server error #### GET /products/{id} **Description**: Retrieves detailed information for a specific product. **Path Parameters**: | Parameter | Type | Required | Description | Example | |-----------|------|----------|-------------|---------| | `id` | integer | Yes | Product ID | `101` | **Success Response (200)**: ```json { "id": 101, "sku": "ELEC-001", "name": "Wireless Bluetooth Headphones", "description": "Noise-cancelling wireless headphones with 30-hour battery", "price": 129.99, "stockQuantity": 50, "categoryId": 5, "category": { "id": 5, "name": "Electronics", "slug": "electronics" }, "images": [ { "id": 1, "url": "https://example.com/products/headphones-1.jpg", "altText": "Front view of headphones", "isPrimary": true, "order": 1 } ], "attributes": [ { "name": "Color", "value": "Black" }, { "name": "Battery Life", "value": "30 hours" } ], "createdAt": "2024-01-10T08:00:00Z", "updatedAt": "2024-01-15T14:30:00Z" } ``` **Error Responses**: - **404** - Product not found - **500** - Internal server error #### POST /products **Description**: Creates a new product in the catalog. Requires ADMIN role. **Request Parameters**: | Parameter | Type | Required | Description | Example | |-----------|------|----------|-------------|---------| | `sku` | string | Yes | Unique product SKU | `"ELEC-002"` | | `name` | string | Yes | Product name | `"Smart Watch Pro"` | | `description` | string | Yes | Product description | `"Advanced smartwatch..."` | | `price` | number | Yes | Product price | `249.99` | | `stockQuantity` | integer | Yes | Initial stock quantity | `100` | | `categoryId` | integer | Yes | Category ID | `5` | | `attributes` | array | No | Product attributes | `[{"name": "Color", "value": "Silver"}]` | **Success Response (201)**: ```json { "id": 102, "sku": "ELEC-002", "name": "Smart Watch Pro", "description": "Advanced smartwatch...", "price": 249.99, "stockQuantity": 100, "categoryId": 5, "createdAt": "2024-01-20T10:00:00Z" } ``` **Error Responses**: - **400** - Validation error - **401** - Authentication required - **403** - Insufficient permissions (non-ADMIN) - **409** - SKU already exists - **500** - Internal server error #### PUT /products/{id} **Description**: Updates an existing product. Only provided fields will be updated. Requires ADMIN role. **Path Parameters**: | Parameter | Type | Required | Description | Example | |-----------|------|----------|-------------|---------| | `id` | integer | Yes | Product ID | `102` | **Request Parameters**: | Parameter | Type | Required | Description | Example | |-----------|------|----------|-------------|---------| | `name` | string | No | Product name | `"Smart Watch Pro V2"` | | `description` | string | No | Product description | `"Updated description"` | | `price` | number | No | Product price | `199.99` | | `stockQuantity` | integer | No | Stock quantity | `75` | | `categoryId` | integer | No | Category ID | `6` | **Success Response (200)**: ```json { "id": 102, "sku": "ELEC-002", "name": "Smart Watch Pro V2", "description": "Updated description", "price": 199.99, "stockQuantity": 75, "categoryId": 6, "updatedAt": "2024-01-25T16:00:00Z" } ``` **Error Responses**: - **400** - Invalid data format - **401** - Authentication required - **403** - Insufficient permissions - **404** - Product not found - **500** - Internal server error #### DELETE /products/{id} **Description**: Soft-deletes a product from the catalog. Requires ADMIN role. **Path Parameters**: | Parameter | Type | Required | Description | Example | |-----------|------|----------|-------------|---------| | `id` | integer | Yes | Product ID | `102` | **Success Response (204)**: No content **Error Responses**: - **401** - Authentication required - **403** - Insufficient permissions - **404** - Product not found - **500** - Internal server error --- ### OrderController **Source Code**: `server/src/main/java/com/example/api/controller/OrderController.java` **Description**: Manages order operations including creation, tracking, and status management. | Endpoint | Method | Description | Security | Status Codes | |----------|--------|-------------|----------|--------------| | `/orders` | POST | Create a new order | JWT Required | 201, 400, 401, 409, 500 | | `/orders` | GET | List current user's orders | JWT Required | 200, 401, 500 | | `/orders/{id}` | GET | Get order details by ID | JWT Required | 200, 401, 403, 404, 500 | | `/orders/{id}/cancel` | POST | Cancel an order | JWT Required | 200, 401, 403, 404, 409, 500 | #### POST /orders **Description**: Creates a new order for the authenticated user. **Request Parameters**: | Parameter | Type | Required | Description | Example | |-----------|------|----------|-------------|---------| | `items` | array | Yes | Order items | See below | | `items[].productId` | integer | Yes | Product ID | `101` | | `items[].quantity` | integer | Yes | Quantity (min: 1) | `2` | | `deliveryAddress` | object | Yes | Delivery address | See below | | `deliveryAddress.street` | string | Yes | Street address | `"123 Main St"` | | `deliveryAddress.city` | string | Yes | City | `"New York"` | | `deliveryAddress.state` | string | Yes | State/Province | `"NY"` | | `deliveryAddress.postalCode` | string | Yes | Postal code | `"10001"` | | `deliveryAddress.country` | string | Yes | Country | `"USA"` | | `billingAddress` | object | No | Billing address (defaults to delivery address) | Same as delivery | | `paymentMethodId` | string | Yes | Payment method identifier | `"pm_123456"` | **Success Response (201)**: ```json { "id": 1001, "orderNumber": "ORD-2024-001", "userId": 1, "totalAmount": 259.98, "status": "PENDING", "orderDate": "2024-01-20T14:30:00Z", "deliveryAddress": { "street": "123 Main St", "city": "New York", "state": "NY", "postalCode": "10001", "country": "USA" }, "items": [ { "productId": 101, "productName": "Wireless Bluetooth Headphones", "quantity": 2, "unitPrice": 129.99, "subtotal": 259.98 } ] } ``` **Error Responses**: - **400** - Validation error (invalid items, missing address) - **401** - Authentication required - **409** - Product out of stock or price changed - **500** - Internal server error #### GET /orders **Description**: Retrieves a paginated list of the authenticated user's orders. **Query Parameters**: | Parameter | Type | Required | Description | Example | |-----------|------|----------|-------------|---------| | `page` | integer | No | Page number (default: 1) | `1` | | `limit` | integer | No | Items per page (default: 20) | `20` | | `status` | string | No | Filter by order status | `"DELIVERED"` | **Success Response (200)**: ```json { "data": [ { "id": 1001, "orderNumber": "ORD-2024-001", "totalAmount": 259.98, "status": "DELIVERED", "orderDate": "2024-01-20T14:30:00Z", "itemCount": 1 } ], "pagination": { "page": 1, "limit": 20, "total": 5, "totalPages": 1 } } ``` **Error Responses**: - **401** - Authentication required - **500** - Internal server error #### GET /orders/{id} **Description**: Retrieves detailed information for a specific order. **Path Parameters**: | Parameter | Type | Required | Description | Example | |-----------|------|----------|-------------|---------| | `id` | integer | Yes | Order ID | `1001` | **Success Response (200)**: ```json { "id": 1001, "orderNumber": "ORD-2024-001", "userId": 1, "totalAmount": 259.98, "status": "DELIVERED", "orderDate": "2024-01-20T14:30:00Z", "shippedDate": "2024-01-21T09:15:00Z", "deliveryAddress": { "street": "123 Main St", "city": "New York", "state": "NY", "postalCode": "10001", "country": "USA" }, "items": [ { "id": 1, "productId": 101, "product": { "id": 101, "name": "Wireless Bluetooth Headphones", "sku": "ELEC-001" }, "quantity": 2, "unitPrice": 129.99, "subtotal": 259.98 } ], "payments": [ { "id": 1, "amount": 259.98, "method": "CREDIT_CARD", "status": "COMPLETED", "paidAt": "2024-01-20T14:31:00Z" } ] } ``` **Error Responses**: - **401** - Authentication required - **403** - Order does not belong to user - **404** - Order not found - **500** - Internal server error #### POST /orders/{id}/cancel **Description**: Cancels a pending order. Only orders with status PENDING or PROCESSING can be cancelled. **Path Parameters**: | Parameter | Type | Required | Description | Example | |-----------|------|----------|-------------|---------| | `id` | integer | Yes | Order ID | `1001` | **Request Parameters**: | Parameter | Type | Required | Description | Example | |-----------|------|----------|-------------|---------| | `reason` | string | No | Cancellation reason | `"Changed my mind"` | **Success Response (200)**: ```json { "id": 1001, "orderNumber": "ORD-2024-001", "status": "CANCELLED", "cancelledAt": "2024-01-22T10:00:00Z", "refund": { "amount": 259.98, "status": "PENDING", "estimatedDays": 3 } } ``` **Error Responses**: - **401** - Authentication required - **403** - Order does not belong to user - **404** - Order not found - **409** - Order cannot be cancelled (already shipped/delivered) - **500** - Internal server error --- ### CategoryController **Source Code**: `server/src/main/java/com/example/api/controller/CategoryController.java` **Description**: Manages product categories including hierarchical category structure. | Endpoint | Method | Description | Security | Status Codes | |----------|--------|-------------|----------|--------------| | `/categories` | GET | List all categories | Public | 200, 500 | | `/categories/{id}` | GET | Get category details | Public | 200, 404, 500 | | `/categories` | POST | Create a new category | JWT Required (ADMIN) | 201, 400, 401, 403, 409, 500 | | `/categories/{id}` | PUT | Update a category | JWT Required (ADMIN) | 200, 400, 401, 403, 404, 500 | | `/categories/{id}` | DELETE | Delete a category | JWT Required (ADMIN) | 204, 401, 403, 404, 409, 500 | #### GET /categories **Description**: Retrieves the full category tree with optional nesting. **Query Parameters**: | Parameter | Type | Required | Description | Example | |-----------|------|----------|-------------|---------| | `includeChildren` | boolean | No | Include child categories (default: true) | `true` | | `parentId` | integer | No | Filter by parent category ID | `1` | **Success Response (200)**: ```json { "data": [ { "id": 1, "name": "Electronics", "slug": "electronics", "parentId": null, "children": [ { "id": 5, "name": "Audio", "slug": "audio", "parentId": 1, "children": [] } ] } ] } ``` #### GET /categories/{id} **Description**: Retrieves detailed information for a specific category. **Path Parameters**: | Parameter | Type | Required | Description | Example | |-----------|------|----------|-------------|---------| | `id` | integer | Yes | Category ID | `5` | **Success Response (200)**: ```json { "id": 5, "name": "Audio", "slug": "audio", "description": "Audio equipment and accessories", "parentId": 1, "parent": { "id": 1, "name": "Electronics", "slug": "electronics" }, "children": [], "productCount": 42 } ``` **Error Responses**: - **404** - Category not found - **500** - Internal server error --- ## API Testing ### cURL Test Commands ```bash # --- Auth --- # Login curl -X POST http://localhost:3000/api/auth/login \ -H "Content-Type: application/json" \ -d '{"email":"test.user@example.com","password":"TestPassword123!"}' # Register curl -X POST http://localhost:3000/api/auth/register \ -H "Content-Type: application/json" \ -d '{"email":"new.user@example.com","password":"SecurePassword123!","name":"New Test User","confirmPassword":"SecurePassword123!"}' # Refresh token curl -X POST http://localhost:3000/api/auth/refresh \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $TOKEN" \ -d '{"refreshToken":"your-refresh-token"}' # Logout curl -X POST http://localhost:3000/api/auth/logout \ -H "Authorization: Bearer $TOKEN" # --- Users --- # Get current user profile TOKEN="your-jwt-token-here" curl -X GET http://localhost:3000/api/users/me \ -H "Authorization: Bearer $TOKEN" # Update user profile curl -X PUT http://localhost:3000/api/users/me \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $TOKEN" \ -d '{"name":"Updated Name","profile":{"phoneNumber":"+0987654321","address":"456 Oak St, City, Country"}}' # Get public user profile curl -X GET http://localhost:3000/api/users/1 # --- Products --- # List products curl -X GET "http://localhost:3000/api/products?page=1&limit=20&categoryId=5" # Search products curl -X GET "http://localhost:3000/api/products?search=headphones&sortBy=price&sortOrder=asc" # Get product details curl -X GET http://localhost:3000/api/products/101 # Create product (ADMIN) curl -X POST http://localhost:3000/api/products \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $TOKEN" \ -d '{"sku":"ELEC-002","name":"Smart Watch Pro","description":"Advanced smartwatch","price":249.99,"stockQuantity":100,"categoryId":5}' # --- Orders --- # Create order curl -X POST http://localhost:3000/api/orders \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $TOKEN" \ -d '{"items":[{"productId":101,"quantity":2}],"deliveryAddress":{"street":"123 Main St","city":"New York","state":"NY","postalCode":"10001","country":"USA"},"paymentMethodId":"pm_123456"}' # List orders curl -X GET http://localhost:3000/api/orders \ -H "Authorization: Bearer $TOKEN" # Get order details curl -X GET http://localhost:3000/api/orders/1001 \ -H "Authorization: Bearer $TOKEN" # Cancel order curl -X POST http://localhost:3000/api/orders/1001/cancel \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $TOKEN" \ -d '{"reason":"Changed my mind"}' # --- Categories --- # List categories curl -X GET http://localhost:3000/api/categories # Get category details curl -X GET http://localhost:3000/api/categories/5 ``` ## Error Codes Reference | Error Code | HTTP Status | Description | |------------|-------------|-------------| | `VALIDATION_ERROR` | 400 | Request validation failed | | `UNAUTHORIZED` | 401 | Authentication required | | `FORBIDDEN` | 403 | Insufficient permissions | | `NOT_FOUND` | 404 | Resource not found | | `CONFLICT` | 409 | Resource conflict (duplicate, state conflict) | | `RATE_LIMIT_EXCEEDED` | 429 | Too many requests | | `INTERNAL_ERROR` | 500 | Server error | ## API Changelog | Version | Date | Changes | |---------|------|---------| | **v1.0.0** | 2024-01-01 | Initial API release | --- *This API documentation is organized by controller classes. Update this document whenever endpoints change.*