Joshua Schaeffer
Joshua Schaeffer

Reputation: 341

Implement a REST API and web interface in Django

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?

Upvotes: 2

Views: 1057

Answers (2)

Shihabudheen K M
Shihabudheen K M

Reputation: 1397

Tastypie is the option for writing RESTfull APIs

You can check the Details here - Tastypie Documentation

Django rest framework is the another best option

Upvotes: 0

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.

Upvotes: 3

Related Questions