Skip to content

Caching

Caching can drastically improve the performance of your API. The caching capabilities provided by REST framework are very similar to those provided by Django's standard caching.

Caching Views

You can use Django's built-in @cache_page decorator to cache the response of views.

Function-Based Views

For function-based views, simply apply the @cache_page decorator before the @api_view decorator.

python
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from rest_framework.decorators import api_view
from rest_framework.response import Response

@cache_page(60 * 15) # Cache for 15 minutes
@api_view(['GET'])
def get_time(request):
    import time
    return Response({'time': time.time()})

Class-Based Views

For class-based views, you can decorate a view method using Django's @method_decorator.

python
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from rest_framework.views import APIView
from rest_framework.response import Response

class TimeView(APIView):
    @method_decorator(cache_page(60 * 15))
    def get(self, request, format=None):
        import time
        return Response({'time': time.time()})

Or you can use it in your URL conf instead of modifying the view directly:

python
from django.urls import path
from django.views.decorators.cache import cache_page
from .views import TimeView

urlpatterns = [
    path('time/', cache_page(60 * 15)(TimeView.as_view())),
]

NOTE

Ensure that your cache backend is properly configured in your Django settings (CACHES), for example using Memcached or Redis.