`# Product & Subscription Platform - Complete API Specification

Base Configuration

  • Base URLhttps://api.yourplatform.com/v1
  • Authentication: JWT Bearer Token + OAuth2
  • Content-Typeapplication/json
  • Rate Limiting: 1000 requests/hour per user

1. Authentication & Authorization APIs

OAuth2 & Social Login

POST /auth/oauth/google
POST /auth/oauth/github

Body:

{
  "code": "authorization_code_from_provider",
  "redirect_uri": "https://yourapp.com/callback"
}

Response:

{
  "access_token": "jwt_token",
  "refresh_token": "refresh_token",
  "expires_in": 3600,
  "user": {
    "user_id": 1,
    "email": "user@example.com",
    "first_name": "John",
    "last_name": "Doe",
    "user_type": "customer"
  }
}

Traditional Authentication

POST /auth/register
POST /auth/login
POST /auth/logout
POST /auth/refresh
POST /auth/forgot-password
POST /auth/reset-password

Register:

{
  "email": "user@example.com",
  "password": "secure_password",
  "first_name": "John",
  "last_name": "Doe",
  "phone": "+1234567890"
}

Login:

{
  "email": "user@example.com",
  "password": "secure_password"
}

Refresh Token:

{
  "refresh_token": "refresh_token_string"
}

2. User Management APIs

User Profile

GET    /users/profile                    # Get current user profile
PUT    /users/profile                    # Update current user profile
DELETE /users/profile                    # Delete current user account

User Administration (Admin/Ops only)

GET    /users                           # List all users (paginated)
GET    /users/{user_id}                 # Get specific user
PUT    /users/{user_id}                 # Update user
DELETE /users/{user_id}                 # Deactivate user
POST   /users/{user_id}/activate        # Activate user

Query Parameters for User List:

?page=1&limit=20&user_type=customer&is_active=true&search=john

3. Role & Permission APIs

Role Management (Admin only)

GET    /roles                           # List all roles
POST   /roles                           # Create new role
GET    /roles/{role_id}                 # Get role details
PUT    /roles/{role_id}                 # Update role
DELETE /roles/{role_id}                 # Delete role

Create Role:

{
  "role_name": "Product Manager",
  "description": "Can manage products and inventory",
  "permissions": {
    "products": ["create", "read", "update", "delete"],
    "inventory": ["read", "update"],
    "orders": ["read"]
  }
}

User Role Assignment

GET    /users/{user_id}/roles           # Get user's roles
POST   /users/{user_id}/roles           # Assign role to user
DELETE /users/{user_id}/roles/{role_id} # Remove role from user

4. Product Management APIs

Product CRUD

GET    /products                        # List products (public)
POST   /products                        # Create product (staff only)
GET    /products/{product_id}           # Get product details
PUT    /products/{product_id}           # Update product (staff only)
DELETE /products/{product_id}           # Delete product (admin only)

Query Parameters:

?page=1&limit=20&product_type=physical&is_active=true&search=laptop&min_price=100&max_price=1000

Create/Update Product:

{
  "name": "Premium Laptop",
  "description": "High-performance laptop for professionals",
  "price": 1299.99,
  "product_type": "physical",
  "sku": "LAPTOP-001",
  "is_active": true
}
GET    /products/search                 # Search products
GET    /products/featured               # Get featured products
GET    /products/popular                # Get popular products

5. Inventory Management APIs

Inventory Operations (Staff only)

GET    /inventory                       # List all inventory
GET    /inventory/{product_id}          # Get product inventory
PUT    /inventory/{product_id}          # Update stock levels
POST   /inventory/{product_id}/adjust   # Adjust stock (with reason)

Update Inventory:

{
  "stock_quantity": 100,
  "reserved_quantity": 5,
  "reorder_level": 10
}

Stock Adjustment:

{
  "adjustment": -5,
  "reason": "Damaged goods removed",
  "reference": "INV-ADJ-001"
}

6. Subscription Management APIs

Subscription Plans

GET    /subscription-plans              # List all plans
POST   /subscription-plans              # Create plan (staff only)
GET    /subscription-plans/{plan_id}    # Get plan details
PUT    /subscription-plans/{plan_id}    # Update plan (staff only)
DELETE /subscription-plans/{plan_id}    # Delete plan (admin only)

Create Subscription Plan:

{
  "product_id": 5,
  "plan_name": "Premium Monthly",
  "description": "Full access to all premium features",
  "price": 29.99,
  "billing_cycle": "monthly",
  "trial_days": 14,
  "is_active": true
}

User Subscriptions

GET    /subscriptions                   # Get user's subscriptions
POST   /subscriptions                   # Create new subscription
GET    /subscriptions/{subscription_id} # Get subscription details
PUT    /subscriptions/{subscription_id} # Update subscription
DELETE /subscriptions/{subscription_id} # Cancel subscription
POST   /subscriptions/{subscription_id}/renew # Renew subscription

7. Order Management APIs

Order Processing

GET    /orders                          # Get user's orders
POST   /orders                          # Create new order
GET    /orders/{order_id}               # Get order details
PUT    /orders/{order_id}               # Update order status (staff only)
DELETE /orders/{order_id}               # Cancel order

Create Order:

{
  "items": [
    {
      "product_id": 1,
      "quantity": 2,
      "unit_price": 99.99
    }
  ],
  "coupon_code": "SAVE10",
  "shipping_address": {
    "street": "123 Main St",
    "city": "New York",
    "state": "NY",
    "zip": "10001",
    "country": "US"
  }
}

Order Administration (Staff only)

GET    /admin/orders                    # List all orders
PUT    /admin/orders/{order_id}/status  # Update order status
POST   /admin/orders/{order_id}/ship    # Mark as shipped
POST   /admin/orders/{order_id}/deliver # Mark as delivered

8. Shopping Cart APIs

Cart Management

GET    /cart                           # Get user's cart
POST   /cart/items                     # Add item to cart
PUT    /cart/items/{item_id}           # Update cart item
DELETE /cart/items/{item_id}           # Remove from cart
DELETE /cart                           # Clear entire cart
POST   /cart/checkout                  # Convert cart to order

Add to Cart:

{
  "product_id": 1,
  "quantity": 2
}

9. Coupon Management APIs

Coupon Operations

GET    /coupons                        # List user's available coupons
POST   /coupons/validate               # Validate coupon code
POST   /coupons/apply                  # Apply coupon to order

Coupon Administration (Staff only)

GET    /admin/coupons                  # List all coupons
POST   /admin/coupons                  # Create coupon
GET    /admin/coupons/{coupon_id}      # Get coupon details
PUT    /admin/coupons/{coupon_id}      # Update coupon
DELETE /admin/coupons/{coupon_id}      # Delete coupon
GET    /admin/coupons/{coupon_id}/usage # Get usage statistics

Create Coupon:

{
  "code": "SUMMER2024",
  "description": "Summer sale discount",
  "discount_type": "percentage",
  "discount_value": 15.00,
  "min_order_amount": 50.00,
  "usage_limit": 1000,
  "valid_from": "2024-06-01",
  "valid_until": "2024-08-31",
  "is_active": true
}

10. Payment APIs

Payment Processing

GET    /payments                       # Get user's payments
POST   /payments/intent                # Create payment intent
POST   /payments/confirm               # Confirm payment
GET    /payments/{payment_id}          # Get payment details
POST   /payments/{payment_id}/refund   # Request refund (staff only)

Create Payment Intent:

{
  "order_id": 123,
  "amount": 199.99,
  "currency": "USD",
  "payment_method": "stripe"
}

Webhook Endpoints

POST   /webhooks/stripe                # Stripe webhook
POST   /webhooks/paypal                # PayPal webhook

11. Invoice Management APIs

Invoice Operations

GET    /invoices                       # Get user's invoices
GET    /invoices/{invoice_id}          # Get invoice details
GET    /invoices/{invoice_id}/pdf      # Download invoice PDF

Invoice Administration (Staff only)

GET    /admin/invoices                 # List all invoices
POST   /admin/invoices                 # Create invoice
PUT    /admin/invoices/{invoice_id}    # Update invoice
POST   /admin/invoices/{invoice_id}/send # Send invoice to customer

12. Notification APIs

User Notifications

GET    /notifications                   # Get user's notifications
PUT    /notifications/{notification_id}/read # Mark as read
DELETE /notifications/{notification_id} # Delete notification
POST   /notifications/mark-all-read    # Mark all as read

Notification Administration (Staff only)

POST   /admin/notifications/send       # Send notification to users
GET    /admin/notifications/templates  # Get notification templates
POST   /admin/notifications/broadcast  # Broadcast to all users

Send Notification:

{
  "user_ids": [1, 2, 3],
  "title": "New Feature Available",
  "message": "Check out our latest feature!",
  "type": "push",
  "metadata": {
    "action_url": "/features/new-feature"
  }
}

13. Analytics & Reporting APIs

User Analytics

GET    /analytics/dashboard            # User dashboard data
GET    /analytics/orders               # Order history analytics
GET    /analytics/subscriptions        # Subscription analytics

Admin Analytics (Admin only)

GET    /admin/analytics/overview       # Platform overview
GET    /admin/analytics/sales          # Sales analytics
GET    /admin/analytics/users          # User analytics
GET    /admin/analytics/products       # Product performance
GET    /admin/analytics/subscriptions  # Subscription metrics

Query Parameters:

?period=30d&start_date=2024-01-01&end_date=2024-01-31&group_by=day

14. Audit & Logging APIs

Audit Logs (Admin only)

GET    /admin/audit-logs               # Get audit logs
GET    /admin/audit-logs/user/{user_id} # Get user's actions
GET    /admin/audit-logs/table/{table}  # Get table changes

Query Parameters:

?action=update&table_name=products&start_date=2024-01-01&page=1&limit=50

15. System & Health APIs

Health Checks

GET    /health                         # Basic health check
GET    /health/detailed                # Detailed system status
GET    /version                        # API version info

System Administration (Admin only)

GET    /admin/system/stats             # System statistics
POST   /admin/system/maintenance       # Enable maintenance mode
DELETE /admin/system/maintenance       # Disable maintenance mode

OAuth2 Implementation Details

Supported Providers

  • Google OAuth2
  • GitHub OAuth2

OAuth2 Flow

  1. Frontend redirects to provider:

    https://accounts.google.com/oauth/authorize?
      response_type=code&
      client_id=YOUR_GOOGLE_CLIENT_ID&
      redirect_uri=https://yourapp.com/callback&
      scope=openid email profile
    
  2. Provider redirects back with code:

    https://yourapp.com/callback?code=AUTHORIZATION_CODE
    
  3. Frontend sends code to your API:

    POST /auth/oauth/google
    {
      "code": "AUTHORIZATION_CODE",
      "redirect_uri": "https://yourapp.com/callback"
    }
  4. API exchanges code for user info and returns JWT:

    {
      "access_token": "jwt_token",
      "refresh_token": "refresh_token",
      "user": { ... }
    }

Environment Variables Needed

# Google OAuth2
GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret
 
# GitHub OAuth2
GITHUB_CLIENT_ID=your_github_client_id
GITHUB_CLIENT_SECRET=your_github_client_secret
 
# JWT
JWT_SECRET=your_jwt_secret
JWT_EXPIRES_IN=1h
REFRESH_TOKEN_EXPIRES_IN=7d

Common Response Formats

Success Response

{
  "success": true,
  "data": { ... },
  "message": "Operation completed successfully"
}

Error Response

{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid input data",
    "details": {
      "email": ["Email is required"],
      "password": ["Password must be at least 8 characters"]
    }
  }
}

Paginated Response

{
  "success": true,
  "data": [...],
  "pagination": {
    "page": 1,
    "limit": 20,
    "total": 150,
    "pages": 8,
    "has_next": true,
    "has_prev": false
  }
}

Authorization Levels

Public Endpoints

  • Product listing
  • Product details
  • Authentication endpoints

User Endpoints (Authenticated)

  • Profile management
  • Orders
  • Subscriptions
  • Cart operations

Staff Endpoints (ops_staff role)

  • Product management
  • Inventory management
  • Order administration
  • Coupon management

Admin Endpoints (admin role)

  • User management
  • Role management
  • System analytics
  • Audit logs
  • System administration

Rate Limiting & Security

Rate Limits

  • Public endpoints: 100 requests/hour
  • Authenticated users: 1000 requests/hour
  • Staff users: 5000 requests/hour
  • Admin users: 10000 requests/hour

Security Headers

Authorization: Bearer <jwt_token>
X-API-Key: <optional_api_key>
X-Request-ID: <unique_request_id>

CORS Configuration

{
  "origin": ["https://yourapp.com", "https://admin.yourapp.com"],
  "methods": ["GET", "POST", "PUT", "DELETE"],
  "allowedHeaders": ["Authorization", "Content-Type", "X-API-Key"]
}

This comprehensive API specification covers all aspects of your product and subscription platform, including OAuth2 integration with Google and GitHub, role-based access control, and full CRUD operations for all entities in your database schema.

ER Diagram

erDiagram
    User {
        int user_id PK
        string email UK
        string password_hash
        string first_name
        string last_name
        string phone
        enum user_type "customer, ops_staff, admin"
        timestamp created_at
        timestamp updated_at
        boolean is_active
    }

    Role {
        int role_id PK
        string role_name UK
        string description
        json permissions
        timestamp created_at
    }

    UserRole {
        int user_role_id PK
        int user_id FK
        int role_id FK
        timestamp assigned_at
        boolean is_active
    }

    Product {
        int product_id PK
        string name
        text description
        decimal price
        enum product_type "physical, software"
        string sku UK
        boolean is_active
        timestamp created_at
        timestamp updated_at
        int created_by FK
    }

    Inventory {
        int inventory_id PK
        int product_id FK
        int stock_quantity
        int reserved_quantity
        int reorder_level
        timestamp last_updated
        int updated_by FK
    }

    SubscriptionPlan {
        int plan_id PK
        int product_id FK
        string plan_name
        text description
        decimal price
        enum billing_cycle "monthly, quarterly, yearly"
        int trial_days
        boolean is_active
        timestamp created_at
        int created_by FK
    }

    Subscription {
        int subscription_id PK
        int user_id FK
        int plan_id FK
        enum status "active, cancelled, expired, trial"
        date start_date
        date end_date
        date next_billing_date
        boolean auto_renew
        timestamp created_at
        timestamp updated_at
    }

    Order {
        int order_id PK
        int user_id FK
        string order_number UK
        enum status "pending, confirmed, shipped, delivered, cancelled"
        decimal subtotal
        decimal tax_amount
        decimal discount_amount
        decimal total_amount
        text shipping_address
        timestamp created_at
        timestamp updated_at
    }

    OrderItem {
        int order_item_id PK
        int order_id FK
        int product_id FK
        int quantity
        decimal unit_price
        decimal total_price
        timestamp created_at
    }

    Coupon {
        int coupon_id PK
        string code UK
        text description
        enum discount_type "percentage, fixed_amount"
        decimal discount_value
        decimal min_order_amount
        int usage_limit
        int used_count
        date valid_from
        date valid_until
        boolean is_active
        timestamp created_at
        int created_by FK
    }

    CouponUsage {
        int usage_id PK
        int coupon_id FK
        int user_id FK
        int order_id FK
        decimal discount_applied
        timestamp used_at
    }

    Notification {
        int notification_id PK
        int user_id FK
        string title
        text message
        enum type "email, sms, push"
        enum status "pending, sent, failed"
        json metadata
        timestamp created_at
        timestamp sent_at
    }

    AuditLog {
        int log_id PK
        int user_id FK
        string table_name
        int record_id
        enum action "create, update, delete"
        json old_values
        json new_values
        string ip_address
        string user_agent
        timestamp created_at
    }

    Payment {
        int payment_id PK
        int user_id FK
        int order_id FK
        int subscription_id FK
        string payment_method
        string external_transaction_id
        decimal amount
        string currency
        enum status "pending, completed, failed, refunded"
        json gateway_response
        timestamp created_at
        timestamp updated_at
    }

    Refund {
        int refund_id PK
        int payment_id FK
        decimal refund_amount
        string reason
        enum status "pending, completed, failed"
        string external_refund_id
        timestamp created_at
        timestamp processed_at
        int processed_by FK
    }

    Invoice {
        int invoice_id PK
        int user_id FK
        int order_id FK
        int subscription_id FK
        string invoice_number UK
        decimal amount
        enum status "draft, sent, paid, overdue, cancelled"
        date due_date
        timestamp created_at
        timestamp sent_at
        int created_by FK
    }

    %% Relationships
    User ||--o{ UserRole : "has"
    Role ||--o{ UserRole : "assigned_to"
    
    User ||--o{ Product : "creates"
    User ||--o{ Inventory : "updates"
    User ||--o{ SubscriptionPlan : "creates"
    User ||--o{ Coupon : "creates"
    User ||--o{ Refund : "processes"
    User ||--o{ Invoice : "creates"
    
    User ||--o{ Order : "places"
    User ||--o{ Subscription : "subscribes"
    User ||--o{ CouponUsage : "uses"
    User ||--o{ Notification : "receives"
    User ||--o{ AuditLog : "performs_action"
    User ||--o{ Payment : "makes"
    User ||--o{ Invoice : "billed_to"
    
    Product ||--o{ Inventory : "has_stock"
    Product ||--o{ SubscriptionPlan : "offers"
    Product ||--o{ OrderItem : "ordered"
    
    SubscriptionPlan ||--o{ Subscription : "subscribed_to"
    
    Order ||--o{ OrderItem : "contains"
    Order ||--o{ CouponUsage : "applies_coupon"
    Order ||--o{ Payment : "paid_by"
    Order ||--o{ Invoice : "invoiced"
    
    Coupon ||--o{ CouponUsage : "used_in"
    
    Payment ||--o{ Refund : "refunded"
    
    Subscription ||--o{ Payment : "recurring_payment"
    Subscription ||--o{ Invoice : "subscription_billing"