Q:

Django Rest Framework - define API from an existing view

I'm writing my django app, and i have a lot of views that already returns a JSONResponse object, for example:
def power_on_relay(request):
'''View that Power on one of the available relays'''
try:
    relay_id = get_or_raise(request, 'relay_id')

    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(relay_id, GPIO.OUT)
    GPIO.output(relay_id, True)
    pin_status = GPIO.input(relay_id)

    return JsonResponse({'success': True, 'message': 'Relay {0} was powered on'.format(relay_id), 'data': None})
except Exception as ex:
    return JsonResponse({'success': False, 'message': str(ex), 'data': ''})

Now, i need to expose some of these views as "API" and i need to manage the authentication, throttling, etc... 
So, i was wondering if it's possible using DRF and without writing tons of redundant code.
I mean, there is a short way to do that? something like a decorator that doesn't change my web application behaivor?
Any suggestions?

A:

You will need to use api_view decorator
from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view(['GET'])
def power_on_relay(request):
    '''View that Power on one of the available relays'''
    try:
        relay_id = get_or_raise(request, 'relay_id')

        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(relay_id, GPIO.OUT)
        GPIO.output(relay_id, True)
        pin_status = GPIO.input(relay_id)

        return Response({'success': True, 'message': 'Relay {0} was powered on'.format(relay_id), 'data': None})
    except Exception as ex:
        return Response({'success': False, 'message': str(ex), 'data': ''})

