Is there a correct/proper approach to implementing a RESTful API and a user interface that uses that API in Django? I have an application that I'd like to create a REST API for and also have a web interface, but I don't know the best approach. Lets say I want to implement the following endpoint: /1.0/transactions. I can create a view for the API
from .models import Transactions
from django.core import serializers
from django.http import HttpResponse
from django.shortcuts import render
from django.views.generic.base import View
class TransactionApiView(View):
def get(self, request):
data = serializers.serialize('json', Transactions.objects.all())
return HttpResponse(data, content_type="application/json")
Now I want to actually render an HTML page with my transactions. I'm thinking there are 3 approaches:
- Call my API which returns a JSON payload and render a template with the data from the payload.
- Duplicate the code from the API in the view that renders the template.
- Implement both an API and user interface in a single class (I don't know if this is even possible).
The first approach would require me to somehow call my view within another view (something I know you shouldn't do), the second approach violates the DRY policy. Provided, in this example there isn't that much code to duplicate, but a POST or a PATCH might result in duplicating a lot more since I might have to validate data or perform other procedures before saving it to the database.
Is there a standard/proper/generally agreed upon approach to this issue?