2

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:

  1. Call my API which returns a JSON payload and render a template with the data from the payload.
  2. Duplicate the code from the API in the view that renders the template.
  3. 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?

2 Answers 2

3

I highly recommend Django REST Framework. A bit of work to setup, but really handles a LOT of the issues that come with setting up a Django RESTful API.

Sign up to request clarification or add additional context in comments.

Comments

0

Tastypie is the option for writing RESTfull APIs

You can check the Details here - Tastypie Documentation

Django rest framework is the another best option

Comments

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.