Django REST Framework Deployment Guide
Prerequisites
- Python 3.10+ (latest patch release recommended)
- Django 4.2, 5.0, 5.1, 5.2, or 6.0 (latest patch release recommended)
- pip package manager
- Database (PostgreSQL, MySQL, SQLite, or other Django-supported databases)
- Web server (for production deployments)
Installation
Install Django REST Framework
pip install djangorestframework
Add to Django Project
- Add
'rest_framework'to yourINSTALLED_APPSsetting insettings.py:
INSTALLED_APPS = [
# ...
"rest_framework",
]
- Configure REST Framework settings (optional but recommended):
REST_FRAMEWORK = {
# Use Django's standard permissions, or allow read-only access for unauthenticated users
"DEFAULT_PERMISSION_CLASSES": [
"rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly",
]
}
Create a New Project (Optional)
If you're starting fresh:
pip install django
pip install djangorestframework
django-admin startproject example .
./manage.py migrate
./manage.py createsuperuser
Configuration
Required Settings
- Database Configuration - Configure your database in
settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'mydatabase',
'USER': 'mydatabaseuser',
'PASSWORD': 'mypassword',
'HOST': 'localhost',
'PORT': '5432',
}
}
-
Authentication - REST Framework supports various authentication methods:
- Basic Authentication (built-in)
- Session Authentication (built-in)
- Token Authentication
- OAuth1a and OAuth2 (via optional packages)
-
CORS - If your API will be accessed from different domains, configure CORS:
INSTALLED_APPS = [
# ...
"rest_framework",
"corsheaders",
]
MIDDLEWARE = [
# ...
"corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware",
]
CORS_ALLOWED_ORIGINS = [
"https://example.com",
"https://sub.example.com",
]
Environment Variables
For production deployments, consider using environment variables for sensitive data:
export SECRET_KEY='your-secret-key'
export DATABASE_URL='postgresql://user:pass@localhost/dbname'
export DEBUG=False
Build & Run
Development Server
./manage.py runserver
Access your API at http://127.0.0.1:8000/
Production Server
For production, use a production-ready WSGI server like Gunicorn:
pip install gunicorn
gunicorn your_project.wsgi:application
Creating API Endpoints
Here's a basic example of creating a user API:
from django.contrib.auth.models import User
from django.urls import include, path
from rest_framework import routers, serializers, viewsets
# Serializers define the API representation
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ["url", "username", "email", "is_staff"]
# ViewSets define the view behavior
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
# Routers provide a way of automatically determining the URL conf
router = routers.DefaultRouter()
router.register(r"users", UserViewSet)
# Wire up our API using automatic URL routing
urlpatterns = [
path("", include(router.urls)),
path("api-auth/", include("rest_framework.urls", namespace="rest_framework")),
]
Deployment
Platform Options
Heroku (Recommended for quick deployment):
# Install Heroku CLI
brew install heroku/brew/heroku
# Login and create app
heroku login
heroku create your-app-name
# Deploy
git push heroku main
# Run migrations
heroku run python manage.py migrate
Docker:
Create a Dockerfile:
FROM python:3.11
ENV PYTHONUNBUFFERED=1
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
RUN python manage.py collectstatic --noinput
CMD ["gunicorn", "your_project.wsgi:application", "--bind", "0.0.0.0:8000"]
Build and run:
docker build -t my-django-app .
docker run -p 8000:8000 my-django-app
AWS Elastic Beanstalk:
- Install EB CLI
- Initialize your application:
eb init - Create environment:
eb create - Deploy:
eb deploy
Production Considerations
-
Static Files - Configure static file serving:
STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') -
Security - Set
DEBUG = Falseand configure security settings:SECURE_SSL_REDIRECT = True SECURE_HSTS_SECONDS = 31536000 SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_PRELOAD = True -
Performance - Consider using caching and database optimization:
CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.redis.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379/1', } }
Troubleshooting
Common Issues
1. ModuleNotFoundError: No module named 'rest_framework'
- Ensure
rest_frameworkis inINSTALLED_APPS - Verify installation:
pip show djangorestframework
2. 404 Not Found on API URLs
- Check that your URLs are properly included in
urls.py - Verify that your ViewSets are correctly registered with the router
3. CSRF Verification Failed
- For API endpoints, use
@csrf_exemptdecorator or configure CSRF settings - Consider using token-based authentication for APIs
4. Database Connection Errors
- Verify database settings in
settings.py - Ensure database server is running
- Check user permissions
5. Serialization Errors
- Ensure your serializer fields match your model fields
- Check for required fields that might be missing in the request data
Debug Mode
Enable debug mode temporarily to get detailed error messages:
# settings.py
DEBUG = True
Logging
Configure logging to help diagnose issues:
# settings.py
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'root': {
'handlers': ['console'],
'level': 'WARNING',
},
'loggers': {
'django': {
'handlers': ['console'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
},
},
}
Performance Issues
- Use Django's built-in query optimization tools
- Implement pagination for large datasets
- Consider using database indexes for frequently queried fields
- Use Django's caching framework to cache expensive operations
Security Issues
- Keep dependencies updated
- Use HTTPS in production
- Implement proper authentication and authorization
- Validate all input data using serializers
- Use Django's built-in security middleware
This guide provides a comprehensive overview of deploying and using Django REST Framework. For more detailed information, refer to the official documentation at https://www.django-rest-framework.org/.