Skip to main content

A powerful command-line tool and web interface for discovering, documenting, and testing API endpoints in Django projects

Project description

๐Ÿš€ Django API Explorer

A powerful command-line tool and web interface for discovering, documenting, and testing API endpoints in Django projects. Automatically extracts URL patterns, HTTP methods, and generates ready-to-use cURL commands with comprehensive dummy data.

โœจ Features

๐Ÿ” Smart API Discovery

  • Automatic URL Pattern Detection: Parse Django URL patterns and DRF routers
  • HTTP Method Detection: Support for GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS
  • Django REST Framework Support: Handle ViewSets, APIViews, and action decorators
  • App-Specific Scanning: Scan individual Django apps or entire projects
  • URL Parameter Extraction: Detect path parameters ({id}, <pk>, (?P<name>...))

๐ŸŽจ Modern Web Interface

  • Interactive Dashboard: Responsive, gradient-based UI with real-time search
  • Shutter System: Click any API row to see detailed cURL commands
  • Smart Filtering: Filter by app, method, or search terms
  • Copy Functionality: One-click copy with visual feedback
  • Auto-reload: Real-time updates when Django files change

๐Ÿ”ง Developer Workflow

  • File Watching: Monitor Django project files for changes
  • Hot Reload: Automatic UI updates without manual refresh
  • CLI Interface: Modern Click-based command-line tool
  • Multiple Output Formats: Terminal, browser, JSON, HTML
  • Custom Ports: Avoid conflicts with existing servers

๐Ÿ“Š Comprehensive Data Generation

  • Smart cURL Commands: Replace URL parameters with sample values
  • Dummy Data: Context-aware payloads for all endpoint types
  • Authentication Headers: Realistic JWT tokens and API keys
  • Complete Coverage: Include all fields, even optional ones
  • Shell Compatibility: Properly escaped for terminal use

๐Ÿ“ค Postman Integration

  • One-Click Export: Export filtered APIs to Postman collection
  • Smart Organization: Group requests by Django app
  • Environment Variables: Pre-configured base URL and auth tokens
  • Parameter Handling: Convert URL parameters to Postman variables
  • Sample Data: Include request bodies for POST/PUT/PATCH
  • Filter-Based Export: Export only selected APIs

๐Ÿš€ Quick Start

Installation

# Clone the repository
git clone <repository-url>
cd api-exporer

# Install dependencies
pip install -r requirements.txt

# Or using pipenv
pipenv install

Basic Usage

# Scan all apps in current Django project
python cli.py --browser

# Scan specific app
python cli.py --app users --browser

# Use custom Django settings
python cli.py --settings myproject.settings.dev --browser

# Enable file watching for auto-reload
python cli.py --app users --browser --watch

# Use custom port to avoid conflicts
python cli.py --app users --browser --watch --port 8005

Advanced Usage

# Export as JSON
python cli.py --json -o apis.json

# Generate cURL commands for terminal
python cli.py --curl

# Specify custom host
python cli.py --host https://api.example.com --browser

# Scan from different project directory
python cli.py --project-root /path/to/django/project --browser

๐Ÿ“– Detailed Documentation

Command Line Options

Option Short Description Default
--project-root -p Django project root path Current directory
--settings -s Django settings module Auto-detect
--app -a Scan specific Django app All apps
--browser -b Open results in browser Terminal output
--watch -w Watch for file changes Disabled
--curl Generate cURL commands Plain URLs
--json -j Output in JSON format Text format
--output -o Save output to file Console output
--host Override host URL From ALLOWED_HOSTS
--port Web server port 8001

Web Interface Features

Interactive Dashboard

  • Real-time Search: Filter endpoints by path, method, or app name
  • App Filtering: Dropdown to filter by Django app
  • Statistics: View total endpoints, methods, and apps
  • Responsive Design: Works on desktop and mobile devices

Shutter System

  • Inline Details: Opens directly below the clicked API row
  • Method Separation: cURL commands grouped by HTTP method
  • Copy Buttons: One-click copy with visual feedback
  • Smart Highlighting: Visual feedback for selected endpoints

cURL Generation

  • Parameter Replacement: URL parameters replaced with sample values
  • Comprehensive Headers: Authentication, Content-Type, User-Agent, etc.
  • Dummy Data: Context-aware sample payloads for POST/PUT requests
  • Shell Compatibility: Properly escaped for terminal use

Postman Export

  • One-Click Export: Export button in the top-right corner
  • Filter-Based Export: Only exports currently filtered endpoints
  • Smart Collection Naming: Names based on active filters
  • App Organization: Groups requests by Django app
  • Environment Variables: Pre-configured base_url, auth_token, api_key
  • Parameter Variables: URL parameters converted to Postman variables
  • Sample Data: Includes request bodies for POST/PUT/PATCH methods
  • Download Ready: Direct download as .json file

File Watching & Auto-Reload

The file watcher monitors your Django project for changes and automatically reloads the UI:

# Enable file watching
python cli.py --browser --watch

# Use custom port
python cli.py --browser --watch --port 8005

Monitored Files:

  • *.py - Python files
  • urls.py - URL configurations
  • views.py - View files
  • models.py - Model files
  • serializers.py - DRF serializers
  • settings.py - Settings files

Ignored Files:

  • __pycache__/
  • *.pyc
  • .git/
  • node_modules/
  • .venv/, venv/, env/
  • .pytest_cache/
  • migrations/

Django Integration

Project Setup

The Django API Explorer integrates seamlessly with your Django project:

# Navigate to your Django project root
cd /path/to/your/django/project

# Run the explorer from your project directory
python /path/to/api-explorer/cli.py --browser

# Or install it as a package and run from anywhere
pip install django-api-explorer
django-api-explorer --browser

Settings Loading

The tool automatically detects and loads Django settings:

# Auto-detection order:
1. Current directory settings
2. Specified --settings module
3. Fallback to minimal settings

# Example with custom settings
python cli.py --settings myproject.settings.dev --browser

Host Detection

Extracts hosts from Django's ALLOWED_HOSTS setting:

# From settings.py
ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'api.example.com']

# Tool will use: http://127.0.0.1:8000 (fallback)

App Discovery

Automatically discovers installed Django apps:

# From settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'myapp',
    'api',
]

URL Pattern Integration

Works with all Django URL pattern types:

# urls.py - Main project URLs
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from myapp.views import UserViewSet

router = DefaultRouter()
router.register(r'users', UserViewSet)

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include(router.urls)),
    path('api/', include('myapp.urls')),
]

# myapp/urls.py - App-specific URLs
from django.urls import path
from . import views

urlpatterns = [
    path('users/', views.UserListView.as_view(), name='user-list'),
    path('users/<int:pk>/', views.UserDetailView.as_view(), name='user-detail'),
]

Django REST Framework Integration

Fully supports DRF patterns and conventions:

# views.py
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    
    @action(detail=True, methods=['post'])
    def activate(self, request, pk=None):
        user = self.get_object()
        user.is_active = True
        user.save()
        return Response({'status': 'activated'})

# The explorer will detect:
# - GET /api/users/ (list)
# - POST /api/users/ (create)
# - GET /api/users/{id}/ (retrieve)
# - PUT /api/users/{id}/ (update)
# - DELETE /api/users/{id}/ (destroy)
# - POST /api/users/{id}/activate/ (custom action)

cURL Command Generation

The tool generates comprehensive cURL commands with:

URL Parameter Replacement

# Original URL: /api/users/{id}/profile/{field}
# Generated: /api/users/1/profile/email

Authentication Headers

# JWT Token
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

# API Key
-H "X-API-Key: api_key_123456789abcdef"

# Client ID
-H "X-Client-ID: client_987654321fedcba"

Sample Data Generation

{
  "name": "Premium Gaming Campaign 2024",
  "description": "High-performance gaming campaign",
  "budget": 50000.00,
  "start_date": "2024-01-01",
  "end_date": "2024-12-31",
  "target_audience": {
    "age_range": "18-35",
    "interests": ["gaming", "technology"],
    "location": "Worldwide"
  }
}

๐Ÿ—๏ธ Project Structure

api-exporer/
โ”œโ”€โ”€ cli.py                 # Main command-line interface
โ”œโ”€โ”€ requirements.txt       # Python dependencies
โ”œโ”€โ”€ README.md             # This documentation
โ”œโ”€โ”€ pyproject.toml        # Project metadata
โ”œโ”€โ”€ MANIFEST.in           # Package manifest
โ”œโ”€โ”€ core/                 # Core functionality
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”œโ”€โ”€ url_extractor.py  # URL pattern extraction
โ”‚   โ”œโ”€โ”€ method_detector.py # HTTP method detection
โ”‚   โ”œโ”€โ”€ settings_loader.py # Django settings loading
โ”‚   โ”œโ”€โ”€ formatter.py      # Output formatting
โ”‚   โ””โ”€โ”€ models.py         # Data models
โ”œโ”€โ”€ web/                  # Web interface
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”œโ”€โ”€ enhanced_server.py # Enhanced HTTP server
โ”‚   โ”œโ”€โ”€ file_watcher_server.py # File watching server
โ”‚   โ””โ”€โ”€ templates/
โ”‚       โ””โ”€โ”€ enhanced_index.html # Main UI template
โ”œโ”€โ”€ utils/                # Utility functions
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ””โ”€โ”€ path_utils.py     # Path utilities
โ””โ”€โ”€ tests/                # Test suite
    โ”œโ”€โ”€ __init__.py
    โ”œโ”€โ”€ test_basic.py     # Basic functionality tests
    โ””โ”€โ”€ test_url_extractor.py # URL extraction tests

๐Ÿ”ง Development

Setup Development Environment

# Clone and setup
git clone <repository-url>
cd api-exporer

# Create virtual environment
python -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

# Install development dependencies
pip install pytest black flake8

Running Tests

# Run all tests
pytest

# Run specific test file
pytest tests/test_basic.py

# Run with coverage
pytest --cov=core --cov=web

Code Quality

# Format code
black .

# Lint code
flake8 .

# Type checking (if using mypy)
mypy .

๐Ÿ› Troubleshooting

Common Issues

Port Already in Use

# Error: OSError: [Errno 48] Address already in use
# Solution: Use different port
python cli.py --browser --port 8005

Django Settings Not Found

# Error: Error loading Django settings
# Solution: Specify settings module
python cli.py --settings myproject.settings.dev --browser

Module Import Errors

# Error: No module named 'some_module'
# Solution: Activate Django project's virtual environment
cd /path/to/django/project
pipenv run python /path/to/api-exporer/cli.py --browser

JavaScript Errors in Browser

# Check browser console for errors
# Common fix: Clear browser cache and reload

Debug Mode

Enable debug output for troubleshooting:

# Set debug environment variable
export DEBUG=1
python cli.py --browser

# Or modify cli.py to add debug logging

๐Ÿค Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Development Guidelines

  • Code Style: Follow PEP 8 and use Black for formatting
  • Testing: Add tests for new features
  • Documentation: Update README.md for new features
  • Type Hints: Use type hints for function parameters and return values

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ™ Acknowledgments

  • Django: For the amazing web framework
  • Django REST Framework: For API development tools
  • Click: For the command-line interface
  • Rich: For beautiful terminal output
  • Watchdog: For file system monitoring

๐Ÿ“ž Support


Made with โค๏ธ for the Django community

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_api_explorer-1.0.0.tar.gz (78.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_api_explorer-1.0.0-py3-none-any.whl (64.5 kB view details)

Uploaded Python 3

File details

Details for the file django_api_explorer-1.0.0.tar.gz.

File metadata

  • Download URL: django_api_explorer-1.0.0.tar.gz
  • Upload date:
  • Size: 78.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.10.11

File hashes

Hashes for django_api_explorer-1.0.0.tar.gz
Algorithm Hash digest
SHA256 45ce0653446fe3fb74eb6d98dbe0871d8d94e71c212156d792633e0ffc0feca2
MD5 aa2e6d2673efe70cb61756adf1112ae6
BLAKE2b-256 ee037646e460fd89441fe131e14244bd076e0d9448a1716de084cdda1a7dc5a9

See more details on using hashes here.

File details

Details for the file django_api_explorer-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for django_api_explorer-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 e7a3eb057d910e4c9e1b85287ac7ab0aca487225359713d7f5d97df70768647a
MD5 ccce8b3d3e5137266057ae62cb09b5e3
BLAKE2b-256 ce723f1e95550cb9410022ec644e1642b5e4dc46500fa46ab61d21d4207e2a98

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page