DEV Community

Cover image for Dynamic API for Django - Free PyPi Library
Sm0ke
Sm0ke

Posted on • Edited on • Originally published at blog.appseed.us

Dynamic API for Django - Free PyPi Library

Hello Coders!

This article presents an open-source library that builds automatically API services for any model defined in a Django application. Once the Dynamic API library is installed, any model enabled in the configuration becomes manageable via a DRF interface secured by JWT tokens. The sources, published on GitHub under the MIT License, can be used in commercial projects or eLearning activities. Thanks for reading!

This library is basically an abstract layer that connects any app model with DRF without writing any code. The coding pattern uses dynamic routing (no model name specialization) and the dynamic imports of the model definition at runtime.

A quick overview of this tool can be found on YouTube - Dynamic API


✨ Library Core Features

The product can be integrated with any Django project using PIP:

$ pip install django-dynamic-api
Enter fullscreen mode Exit fullscreen mode

Once the library is installed, we should be able to activate API services on top of any app model in no time.

  • βœ… API engine provided by DRF
  • βœ… Secured by JWT Tokens (mutating requests)
  • βœ… Minimal Configuration (single line in the config)
  • βœ… GET requests are public
  • βœ… Update, Delete, and Creation requests are protected

Dynamic API Service - DRF UI Interface


✨ How to use the product

This section presents all the necessary steps to code a simple Django project with a production-ready API provided by the Dynamic API library.

πŸ‘‰ Step #1 - Clone a basic Django Starter: Core Django

This simple codebase comes with minimal structure and Docker support. Feel free to use your own codebase.

$ git clone https://github.com/app-generator/core-django.git
$ cd core-django
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Step #2 - Create virtual environment and install Django

$ virtualenv env
$ source env/bin/activate
$ pip install -r requirements.txt
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Step #3 - Migrate database

$ python manage.py makemigrations
$ python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Step #4 - Create SuperUser and start the app

$ python manage.py createsuperuser 
$ python manage.py runserver
Enter fullscreen mode Exit fullscreen mode

The superuser credentials are required later in API usage.

At this point, we have a basic Django starter ready to be used and extended with more features. Let's move on with our tutorial and code a simple app that defines a Book model.


πŸ‘‰ Step #5 - Create a new APP

$ django-admin startapp app1
Enter fullscreen mode Exit fullscreen mode

This command executed in the root of the project will create a skeleton app. In order to make it more useful, we will define a simple model, managed later by the Dynamic API library.

class Book(models.Model):

    title = models.CharField(max_length=100)
    info  = models.CharField(max_length=100, default='')
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Step #6 - Configure the new app and migrate the database

Each time a Django project got a new app, the configuration should be updated in order to actually use it in the code:

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",

    "app1", # <-- NEW
]
Enter fullscreen mode Exit fullscreen mode

The migration step is also mandatory for all the new apps:

$ python manage.py makemigrations
$ python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

Our sample Django codebase is stable and has a model ready to be used via the Dynamic API library. Let's install the tool and use it.


πŸ‘‰ Step #7 - Install Dynamic API Package

$ pip install django-dynamic-api
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Step #8 - Update APPs section to include the library

INSTALLED_APPS = [
...
    'django_dyn_api',            # Django Dynamic API  # <-- NEW
    'rest_framework',            # Include DRF         # <-- NEW 
    'rest_framework.authtoken',  # Include DRF Auth    # <-- NEW   
...    
]
Enter fullscreen mode Exit fullscreen mode

At the end of the settings file, we need to add a new section used by the DYNAMIC Api module:

DYNAMIC_API = {
    # API_SLUG -> Import_PATH 
    'books'  : "app1.models.Book",
}

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ],
}
Enter fullscreen mode Exit fullscreen mode

DYNAMIC_API section informs the library to manage the Book model under the books API route.

This configuration part is crucial in order to have a stable API service.


πŸ‘‰ Step #9 - Migrate (again) the database

The migration is required by the DRF library, especially by the JWT token management part.

$ python manage.py makemigrations
$ python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Step #10 - Update configuration

from django.contrib import admin
from django.urls import path, include  # <-- NEW: 'include` directive
from rest_framework.authtoken.views import obtain_auth_token # <-- NEW

urlpatterns = [
    path("admin/", admin.site.urls),
    path('', include('django_dyn_api.urls')),    # <-- NEW: API routing rules
    path('login/jwt/', view=obtain_auth_token),  # <-- NEW
] 
Enter fullscreen mode Exit fullscreen mode

At this point, the new API can be accessed in the browser via 3rd party tools like POSTMAN.

Dynamic API Service - Usage in POSTMAN.


The full source code used in this demonstration can be found on GitHub, available for curious minds as reference.

GitHub logo app-generator / core-django-dyn-api

Django Dynamic API - Complete Sample | AppSeed

Minimal Django project with Docker support - actively supported by AppSeed via Email and Discord.

Features - see video presentation

  • βœ… Up-to-date Dependencies
  • βœ… Docker
  • βœ… Integrates Dynamic API Library Library for Django

✨ Start the app in Docker

πŸ‘‰ Step 1 - Download the code from the GH repository (using GIT)

$ git clone https://github.com/app-generator/core-django-dyn-api.git
$ cd core-django-dyn-api
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Step 2 - Start the APP in Docker

$ docker-compose up --build 
Enter fullscreen mode Exit fullscreen mode

Visit http://localhost:5085 in your browser. The app should be up & running.


Manual Build

πŸ‘‰ Download the code

$ git clone https://github.com/app-generator/core-django-dyn-api.git
$ cd core-django-dyn-api
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Install modules via VENV

$ virtualenv env
$ source env/bin/activate
$ pip install -r requirements.txt
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Set Up Database

$ python manage.py makemigrations
$ python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Start the app

$ python manage.py runserver
Enter fullscreen mode Exit fullscreen mode

At this point, the app runs at http://127.0.0.1:8000/.


Django Dynamic API - DRF Interface (open-source tool).



Django Dynamic…


Thanks for reading! For more tools and support feel free to access:

Top comments (6)

Collapse
 
glowreeyah profile image
Gloria Asuquo

Very nice article πŸ‘πŸ½πŸ‘πŸ½

Collapse
 
sm0ke profile image
Sm0ke

Ty Gloria

Collapse
 
crearesite profile image
WebsiteMarket

Nice tool.

Collapse
 
sm0ke profile image
Sm0ke

πŸš€πŸš€

Collapse
 
uithemes profile image
ui-themes

Thanks for sharing.

Collapse
 
sm0ke profile image
Sm0ke

πŸš€πŸš€