Building a REST API with Django REST Framework: Complete Guide
# Building a REST API with Django REST Framework
Django REST Framework (DRF) is the most popular library for building APIs in Python. In this comprehensive guide, we'll build a complete API from scratch.
## Why Django REST Framework?
DRF provides:
- Browsable API interface for easy testing
- Serialization for complex data types
- Authentication and permissions out of the box
- Pagination, filtering, and throttling
- Excellent documentation
## Setting Up Your Project
```python
# Install dependencies
pip install django djangorestframework
# Create a new Django project
django-admin startproject myapi
cd myapi
python manage.py startapp core
```
## Configuring DRF
Add to your `settings.py`:
```python
INSTALLED_APPS = [
# ...
'rest_framework',
'core',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 20,
}
```
## Creating Models
```python
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=200)
description = models.TextField()
price = models.DecimalField(max_digits=10, decimal_places=2)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
```
## Building Serializers
Serializers convert complex data types to JSON:
```python
from rest_framework import serializers
from .models import Product
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ['id', 'name', 'description', 'price', 'created_at']
read_only_fields = ['created_at']
```
## Creating ViewSets
ViewSets combine the logic for multiple views:
```python
from rest_framework import viewsets
from .models import Product
from .serializers import ProductSerializer
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
filterset_fields = ['name', 'price']
search_fields = ['name', 'description']
ordering_fields = ['price', 'created_at']
```
## URL Configuration
```python
from rest_framework.routers import DefaultRouter
from core.views import ProductViewSet
router = DefaultRouter()
router.register('products', ProductViewSet)
urlpatterns = router.urls
```
## Authentication
Implement token authentication:
```python
from rest_framework.authtoken.models import Token
from django.contrib.auth.models import User
# Create token for user
token, created = Token.objects.get_or_create(user=user)
```
## Testing Your API
Use the browsable API or tools like:
- Postman
- HTTPie
- curl
## Best Practices
1. **Version your API**: Use URL versioning (`/api/v1/`)
2. **Document everything**: Use drf-spectacular for OpenAPI docs
3. **Handle errors gracefully**: Return consistent error responses
4. **Implement rate limiting**: Protect against abuse
5. **Write tests**: Ensure reliability with automated testing
## Next Steps
Now that you have the basics, explore:
- Custom permissions
- Nested serializers
- File uploads
- WebSocket integration
Check out our Django API boilerplates in the marketplace for production-ready templates!