Using Django API is easy with built-in templates

You can easily use simple APIs without configuring an external frontend. Here's how to use Django templates for API programming.

You can easily use simple APIs without configuring an external frontend. Here's how to use Django templates for API programming .

Picture 1 of Using Django API is easy with built-in templates

When using backend technology or frameworks like Django, Laravel or Node.js to write REST APIs, you need to gain additional frontend skills by using frameworks like React, Angular, Vue to use API endpoints. But not all cases are like that. You can use the API in Django using available templates.

Set up Django project and API Endpoint

The first step is to create the project folder. Open your terminal and create a directory for the project.

mkdir payment_wallet_project cd payment_wallet_project

In this tutorial, you will build an API for a payment wallet.

Start by creating a virtual environment. In this case, you will use the Pipenv library.

pipenv install django djangorestframework

This command installs the necessary libraries as well as creates a virtual environment. Activate the virtual environment using the command below:

pipenv shell

Create a new Django project named PayApp .

pipenv shell

Using a period (.) at the end of the django-admin command ensures this project avoids creating a duplicate folder in the project directory.

Create a new Django app in the project directory.

python manage.py startapp wallet

Now, continue building the API app using the steps below.

Create a payment wallet using REST API

Open the wallet/models.p y file and locate the wallet and transaction patterns.

from django.db import models class Wallet(models.Model): user = models.CharField(max_length=100) balance = models.DecimalField(max_digits=10, decimal_places=2) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) def __str__(self): return self.user class Transaction(models.Model): wallet = models.ForeignKey(Wallet, on_delete=models.CASCADE) amount = models.DecimalField(max_digits=10, decimal_places=2) timestamp = models.DateTimeField(auto_now_add=True)

In the wallet folder , create a new file serializers.py , programming the wallet and transaction model serializers.

from rest_framework import serializers from .models import Wallet, Transaction class WalletSerializer(serializers.ModelSerializer): class Meta: model = Wallet fields = '__all__' class TransactionSerializer(serializers.ModelSerializer): class Meta: model = Transaction fields = '__all__'

This serializer looks at all the fields in the wallet and the transaction pattern.

In wallet/views.py , write viewers to handle the logic that implements wallet functionality, including deposits and withdrawals.

from rest_framework import generics, status from rest_framework.response import Response from rest_framework.decorators import action from decimal import Decimal from .models import Wallet, Transaction from .serializers import WalletSerializer, TransactionSerializer class WalletViewSet(viewsets.ModelViewSet): queryset = Wallet.objects.all() serializer_class = WalletSerializer @action(detail=True, methods=['post']) def deposit(self, request, pk=None): wallet = self.get_object() amount = Decimal(request.data['amount']) wallet.balance += amount wallet.save() serializer = WalletSerializer(wallet) return Response(serializer.data) @action(detail=True, methods=['post']) def withdraw(self, request, pk=None): wallet = self.get_object() amount = Decimal(request.data['amount']) if wallet.balance < amount: return Response({'error': 'Insufficient funds'}, status=status.HTTP_400_BAD_REQUEST) wallet.balance -= amount wallet.save() serializer = WalletSerializer(wallet) return Response(serializer.data)' class TransactionViewSet(viewsets.ModelViewSet): queryset = Transaction.objects.all() Serializer_class = TransactionSerializer

Next, define the URL route for the API by creating the wallet/urls.py file :

from django.urls import path, include from rest_framework.routers import DefaultRouter from .views import WalletViewSet, TransactionViewSet, wallet_view router = DefaultRouter() router.register(r'wallets', WalletViewSet, basename='wallets') router.register(r'transactions', TransactionViewSet, basename='transactions') urlpatterns = [ path('api/', include(router.urls)), path('wallets//deposit/', WalletViewSet.as_view({'post': 'deposit'}), name='wallet-deposit'), path('wallets//withdraw/', WalletViewSet.as_view({'post': 'withdraw'}), name='wallet-withdraw'), ]

In the project's urls.py , include the application URL:

from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('wallet.urls')), ]

In the PayApp/settings.py file , add wallet and rest_framwork apps to the INSTALLED_APPS list .

INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "rest_framework", # new "wallet", # new ]

This will register the app wallet and rest_framework for the Django project application.

Use the API with Django templates

Now, you'll use Django templates to create a simple frontend for consuming the API. Create the wallet.html file in the wallet/templates/ folder and add the HTML code below:

 Wallet 

Wallets

User Balance Actions
{{ wallet.user }} {{ wallet.balance }} Loading.

Please wait while the deposit is being processed.

{% csrf_token %}{% csrf_token %}

This HTML file shows the transfer and withdrawal API in a beautiful user interface designed by Bootstrap.

User interaction with forms

In the HTML file, create a script tag and add the following code to the remittance form submission event handler.

Next, add an event listener for the withdrawal form submission using the code below:

The event listener is responsible for handling deposit and withdrawal form submissions ( #deposit-form & #withdraw-form ).

Query fetch URL is for combining URLs for transfer and withdrawal actions.

JSON responses to transfer and withdrawal tasks are then parsed to update the balance ( data.balance ). Next, they will be formatted and displayed on this page.

In wallet/views.py , add the following update to display the wallet.html page :

from django.shortcuts import render def wallet_view(request): # Retrieve the wallet to display wallet = Wallet.objects.first() return render(request, 'wallet.html', {'wallet': wallet})

In this example, you will use the first() query method to select a user's wallet for demonstration purposes.

Update the urls.py file by adding the path to wallet_view as follows:

from .views import wallet_view urlpatterns = [ . path('home/', wallet_view, name='wallet-page'), ]

Access the wallet's page from: http://127.0.0.1:8000/home/ .

With everything set up and working as expected, execute the makemigrations and migrate commands . Finally, run the application:

python manage.py makemigrations python manage.py migrate python manage.py runserver

To access API endpoints, navigate to http://127.0.0.1:8000/api/ .

The result is as good as we expected:

Picture 2 of Using Django API is easy with built-in templates

Navigate to localhost to interact with the wallet.

Result:

Picture 3 of Using Django API is easy with built-in templates

This wallet shows your account balance and gives you the option to deposit or withdraw money.

Some limitations when using the Django templates API:

  1. Limited flexibility.
  2. Asynchronous queries are not supported.
  3. Limited error handling.

Overall, Django templates allow programmers to focus on creating reusable and maintainable code. However, due to their limitations, Django templates may not be the best choice when using APIs at scale. Client frameworks like React are still useful in building scalable applications.

Update 13 October 2023
Category

System

Mac OS X

Hardware

Game

Tech info

Technology

Science

Life

Application

Electric

Program

Mobile