You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

8.2 KiB

Imam Javad API Documentation System

Overview

This project implements a comprehensive custom API documentation system that replaces the default Swagger UI with a beautiful, secure, and user-friendly interface. The system is designed specifically for the Imam Javad educational platform and includes advanced authentication, responsive design, and professional styling.

Features

🔐 Security & Access Control

  • Admin-only access: All documentation endpoints require staff member authentication
  • Token-based authentication: Secure API token management for testing endpoints
  • Session management: Persistent authentication state across documentation systems
  • Automatic redirects: Unauthorized users are redirected to admin login

🎨 Custom Documentation Interface

  • Responsive sidebar navigation: Collapsible app sections with smooth animations
  • Interactive endpoint explorer: Click to navigate and highlight specific endpoints
  • Beautiful JSON viewer: Syntax-highlighted response examples with Prism.js
  • Mobile-friendly design: Optimized for all screen sizes
  • Professional styling: Modern gradient backgrounds and smooth transitions

🔧 Enhanced Swagger UI

  • Fixed authentication banner: Always-visible user info and token management
  • Custom branding: Imam Javad themed colors and styling
  • Token injection: Automatic authorization header injection for API testing
  • Integrated navigation: Seamless links between documentation systems

System Architecture

File Structure

apps/api/views/
├── __init__.py
├── documentation.py      # Custom documentation view
├── swagger_views.py      # Enhanced Swagger views with auth
└── api_views.py         # Original API views

templates/
├── api/
│   └── documentation.html    # Main documentation template
└── swagger/
    ├── ui.html              # Custom Swagger UI template
    └── auth.html            # Token authentication template

config/
├── urls.py                  # Updated URL configuration
└── enhanced_auth_middleware.py  # Custom authentication middleware

URL Endpoints

Documentation System

  • /en/docs/ - Main API documentation interface
  • /en/swagger/ - Enhanced Swagger UI with authentication
  • /en/swagger-auth/ - Token authentication management
  • /en/swagger-auth/clear/ - Clear authentication session
  • /en/redoc/ - Protected ReDoc interface

API Structure

The documentation covers all major app endpoints:

  • Account Management (/api/account/) - User auth, registration, profiles
  • Course System (/api/courses/) - Educational courses and lessons
  • Hadis Collection (/api/hadis/) - Islamic hadis texts and categories
  • Digital Library (/api/library/) - Books and downloadable resources
  • Video Content (/api/videos/) - Educational video content
  • Podcast Platform (/api/podcast/) - Audio content and episodes
  • Quiz System (/api/quiz/) - Interactive assessments
  • Bookmarks & Ratings (/api/bookmarks/) - User content management

Setup Instructions

1. Authentication Setup

The system automatically creates middleware that handles authentication for protected paths. Admin users get automatic token generation for API access.

2. Admin User Creation

# Create admin user (already done in implementation)
from apps.account.models import User
from rest_framework.authtoken.models import Token

admin_user = User.objects.create(
    email='admin@imamjavad.com',
    fullname='Admin User',
    is_staff=True,
    is_superuser=True,
    user_type=User.UserType.SUPER_ADMIN
)
admin_user.set_password('admin123')
admin_user.save()

# Get admin token for API testing
token, _ = Token.objects.get_or_create(user=admin_user)
print(f"Admin token: {token.key}")

3. Accessing the Documentation

  1. Login to Admin Panel: Visit /en/admin/ and login with admin credentials
  2. Access Documentation: Navigate to /en/docs/ for the main documentation
  3. Use Swagger UI: Visit /en/swagger/ for interactive API testing
  4. Manage Tokens: Use /en/swagger-auth/ for token authentication

Usage Guide

Main Documentation Interface

  1. Sidebar Navigation:

    • Click on app names to expand/collapse endpoint lists
    • Click on specific endpoints to scroll to their documentation
    • Mobile users can toggle sidebar with the hamburger menu
  2. Endpoint Documentation:

    • Each endpoint shows HTTP method, URL, and description
    • Parameters table with types and requirements
    • Interactive response examples with syntax highlighting
    • Tabbed interface for different response types
  3. Action Buttons:

    • "Swagger UI" button links to interactive testing interface
    • "ReDoc" button provides alternative documentation view

Swagger UI Interface

  1. Authentication Banner:

    • Shows current user information and authentication status
    • Provides quick access to token management
    • Links to main documentation
  2. Token Management:

    • Enter 40-character API tokens for testing
    • Automatic token injection into API requests
    • Session persistence across page reloads
  3. API Testing:

    • All endpoints automatically include authentication headers
    • Interactive request/response testing
    • Real-time API exploration

Customization

Adding New Endpoints

Update the _get_api_structure() method in apps/api/views/documentation.py:

def _get_api_structure(self):
    return {
        'new_app': {
            'name': 'New App Name',
            'description': 'App description',
            'endpoints': [
                {
                    'name': 'Endpoint Name',
                    'method': 'GET',
                    'url': '/api/new-app/endpoint/',
                    'description': 'Endpoint description',
                    'parameters': [...],
                    'response_examples': {...}
                }
            ]
        }
    }

Styling Customization

Modify CSS variables in templates/api/documentation.html:

:root {
    --primary-color: #2c3e50;
    --secondary-color: #3498db;
    --success-color: #27ae60;
    /* Add your custom colors */
}

Branding Updates

  • Update project name in templates and views
  • Modify color schemes and gradients
  • Add custom logos and icons
  • Update contact information and licensing

Security Considerations

Access Control

  • All documentation endpoints require @staff_member_required decorator
  • Middleware automatically handles authentication for protected paths
  • Session-based token management with validation
  • Automatic cleanup of invalid tokens

Token Security

  • 40-character Django REST framework tokens
  • Session storage with server-side validation
  • Automatic token refresh and cleanup
  • User activity tracking and session management

Troubleshooting

Common Issues

  1. 403 Forbidden on Documentation Pages

    • Ensure user has is_staff=True
    • Check middleware configuration
    • Verify admin login session
  2. Token Authentication Not Working

    • Verify token is exactly 40 characters
    • Check token exists in database
    • Ensure user account is active
  3. Responsive Design Issues

    • Clear browser cache
    • Check viewport meta tag
    • Test on different screen sizes

Debug Mode

Enable Django debug mode to see detailed error messages:

DEBUG = True  # in settings

Performance Optimization

Caching

  • Static assets are cached with appropriate headers
  • JSON responses use browser caching
  • Template fragments can be cached for better performance

Mobile Optimization

  • Responsive images and media queries
  • Touch-friendly interface elements
  • Optimized loading for mobile networks

Contributing

When adding new features or endpoints:

  1. Update the API structure in documentation.py
  2. Add appropriate response examples
  3. Test on multiple screen sizes
  4. Ensure security requirements are met
  5. Update this documentation

License

This documentation system is part of the Imam Javad educational platform and follows the project's MIT License.


Admin Credentials for Testing:

  • Email: admin@imamjavad.com
  • Password: admin123
  • API Token: 632a324083da7c224361fc61eb5882633c1c575b