6.7 KiB
Django Enhanced API Docs
Enhanced API documentation for Django REST Framework using drf-spectacular with custom schema generation, automatic parameter descriptions, and code samples.
Features
- Optional API Documentation: Enable/disable API docs via environment variable
- Enhanced Schema Generation: Automatic parameter descriptions for filters, search, ordering, and pagination
- Language Support: Built-in support for translatable fields with language parameter
- Code Samples: Automatic cURL code sample generation for all endpoints
- Custom Tags: Organize endpoints with custom tags mapped to ViewSet classes
- Comprehensive Error Responses: Automatic addition of standard HTTP error responses
- Pagination Examples: Dynamic pagination URL examples based on actual endpoints
Installation
Via pip (when published)
pip install django-enhanced-apidocs
Via Git (development)
pip install git+https://github.com/yourusername/django-enhanced-apidocs.git
As Git Submodule (development)
cd your-django-project
git submodule add https://github.com/yourusername/django-enhanced-apidocs.git
pip install -e ./django-enhanced-apidocs
Editable Installation (local development)
pip install -e /path/to/django-enhanced-apidocs
Configuration
1. Add to INSTALLED_APPS
Add the following to your Django settings.py:
# Enable API documentation (default: enabled in DEBUG mode)
ENABLE_API_DOCS = os.environ.get('ENABLE_API_DOCS', str(DEBUG)).lower() in ('true', '1', 'yes')
INSTALLED_APPS = [
# ... your other apps
]
# Conditionally add API documentation
if ENABLE_API_DOCS:
INSTALLED_APPS.extend(['drf_spectacular', 'django_enhanced_apidocs'])
2. Configure REST Framework
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 20,
}
# Set schema class when API docs are enabled
if ENABLE_API_DOCS:
REST_FRAMEWORK['DEFAULT_SCHEMA_CLASS'] = 'django_enhanced_apidocs.schema.CustomAutoSchema'
3. Import Spectacular Settings
# In settings.py
if ENABLE_API_DOCS:
from django_enhanced_apidocs.conf import get_spectacular_settings
# Pass your dotenv config dict
SPECTACULAR_SETTINGS = get_spectacular_settings(config)
The config parameter should be a dictionary with at least:
LOCAL_SWAGGER_HOST(optional): Server URL for API documentation (default: 'http://localhost:8000')
You can also override settings after import:
if ENABLE_API_DOCS:
from django_enhanced_apidocs.conf import get_spectacular_settings
SPECTACULAR_SETTINGS = get_spectacular_settings(config)
# Customize settings
SPECTACULAR_SETTINGS['TITLE'] = 'My API'
SPECTACULAR_SETTINGS['DESCRIPTION'] = 'My API Description'
SPECTACULAR_SETTINGS['VERSION'] = '2.0.0'
SPECTACULAR_SETTINGS['CONTACT'] = {'email': 'api@example.com'}
4. Include URLs
Add documentation URLs to your urls.py:
from django.urls import path, include
from django.conf import settings
urlpatterns = [
# Your API endpoints
path('api/v1/', include('your_app.urls')),
]
# Conditionally include API documentation URLs
if getattr(settings, 'ENABLE_API_DOCS', False):
urlpatterns.append(path('', include('django_enhanced_apidocs.urls')))
This adds the following endpoints:
/swagger/- Swagger UI/redoc/- ReDoc UI/api/schema/- OpenAPI JSON schema
Environment Variables
Control API documentation via environment variables:
# Enable API docs (default: true in DEBUG mode)
ENABLE_API_DOCS=true
# Set custom server URL for API docs
LOCAL_SWAGGER_HOST=http://localhost:8000
Or in your .env file:
ENABLE_API_DOCS=false # Disable in production
LOCAL_SWAGGER_HOST=https://api.example.com
Custom Tags Configuration
The package comes with pre-configured tags for common Django apps. You can customize them in your settings:
if ENABLE_API_DOCS:
from django_enhanced_apidocs.conf import get_spectacular_settings
SPECTACULAR_SETTINGS = get_spectacular_settings(config)
# Add custom tags
SPECTACULAR_SETTINGS['TAGS'] = [
{
'name': 'Products',
'description': 'Product management endpoints',
'viewsets': ['ProductViewSet', 'ProductVersionViewSet']
},
{
'name': 'Users',
'description': 'User management endpoints',
'viewsets': ['UserViewSet']
},
]
Features in Detail
Automatic Parameter Descriptions
The package automatically enhances query parameters with human-readable descriptions:
- Search: Describes which fields are searched
- Ordering: Explains ascending/descending syntax
- Pagination: Documents page number format
- Filters: Generates descriptions based on field types (boolean, integer, foreign key, etc.)
Language Parameter
For projects using translatable fields (e.g., django-translatable-fields), the package automatically adds a lang parameter to GET endpoints:
?lang=en # Returns English translations
?lang=de # Returns German translations
?lang=fr # Returns French translations
Automatic cURL Code Samples
Every endpoint includes a ready-to-use cURL command with:
- Correct HTTP method
- Authentication headers
- Request body (for POST/PUT/PATCH)
- Sample data based on serializer schema
Standard Error Responses
All endpoints automatically document standard HTTP error responses:
- 400 Bad Request
- 401 Unauthorized
- 403 Forbidden
- 404 Not Found
- 409 Conflict
- 500 Internal Server Error
Usage Example
After installation, access your API documentation at:
- Swagger UI: http://localhost:8000/swagger/
- ReDoc: http://localhost:8000/redoc/
- OpenAPI Schema: http://localhost:8000/api/schema/
Disabling in Production
To disable API documentation in production:
# In your production .env file
ENABLE_API_DOCS=false
Or in your settings:
ENABLE_API_DOCS = False
When disabled:
/swagger/,/redoc/,/api/schema/return 404drf_spectacularanddjango_enhanced_apidocsare not loaded- No performance impact on API endpoints
Requirements
- Python >= 3.9
- Django >= 4.0
- djangorestframework >= 3.14
- drf-spectacular >= 0.26
License
MIT License - see LICENSE file for details
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Credits
Created by KBS GmbH