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 .

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

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:

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

Navigate to localhost to interact with the wallet.

Result:

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

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.

4.5 ★ | 2 Vote

May be interested

  • Model Inheritance là gì trong Django?Model Inheritance là gì trong Django?
    inheritance - kế thừa cho phép bạn dùng lại code và tạo mẫu dữ liệu gọn gàng hơn. thế nhưng django cung cấp nhiều hơn một cách để kế thừa, vì thế, đảm bảo bạn biết rõ các điểm khác biệt.
  • 12 stunning HTML5 templates that web designers should not ignore12 stunning HTML5 templates that web designers should not ignore
    there are many free html5 templates online and choose one of them that can make it difficult for many people. therefore, the article scoured the internet to bring you stunning html5 templates for business, personal, portfolio profiles, and all other types of websites.
  • The best Microsoft OneNote download sitesThe best Microsoft OneNote download sites
    onenote provides a complete set of tools to create templates, but you can save time by downloading templates available from the web.
  • Beautiful free PowerPoint slides for office workersBeautiful free PowerPoint slides for office workers
    thanks to tools like powerpoint, meetings are less 'miserable'. it is a support tool and keeps the meeting circuit smoothly. even slie powerpoint templates can shorten time and bring higher work efficiency. below, you will discover powerpoint slides.
  • Beautiful free PowerPoint slides for teachersBeautiful free PowerPoint slides for teachers
    whether you are teaching a class, teaching lectures, running an instructional program or training students, the following powerpoint slides are perfect choices. some templates provide you with tables, charts and diagrams, while others provide you with simple educational theme themes that match your presentation.
  • How to create a movie ticket booking system using DjangoHow to create a movie ticket booking system using Django
    programming a movie ticket booking system using django is not difficult. below is a detailed step-by-step guide on how to book movie tickets using django.
  • 12 great free Keynote templates for your presentation12 great free Keynote templates for your presentation
    if you use apple's keynote, it is best to use the keynote templates available to create impressive presentations that serve many different purposes such as business, health, education, etc.
  • 10 free PowerPoint templates to present your photos with style10 free PowerPoint templates to present your photos with style
    you might think photoshop is the best tool for stitching photos together, but really, powerpoint offers a ton of free templates for you to use for the same purpose. here are all the best powerpoint photo collage templates you have to choose from.
  • 5 best Google Slides templates for teachers5 best Google Slides templates for teachers
    google slides is one of the best and free presentation apps out there. this tool uses a simple approach that makes it quick and easy to create and present slides for teachers and education professionals.
  • 5 reliable sources of slideshow templates for presentations5 reliable sources of slideshow templates for presentations
    with so many slideshow templates available, finding the best among quality templates can be a challenge.