0

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?

1 Answer 1

2

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': ''})
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, and how i can implement the documentation of these api? i mean, there is some CLEAN way to document the parameter that i need to give to the endpoint api?
@VirtApp I think that in your situation you should use explicit schema definition django-rest-framework.org/api-guide/schemas/… But over time it could become hard to maintain. I would adivise that you start refactoring your views into class based ones. This will reduce boilerplate and will give you auto generated API documentation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.