Dynamic API for Django - Free PyPi Library
Tags: webdev, django, opensource, tools
Published: 2022-10-24 15:39:41

---
title: Dynamic API for Django - Free PyPi Library
published: true
description: An open-source PyPi Library that builds automatically Dynamic APIs on top of DRF with minimum effort - Released under the MIT License on Github.
tags: webdev, django, opensource, tools
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gsii9d73stt8ustsvfil.jpg
canonical_url: https://blog.appseed.us/dynamic-api-for-django-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](https://github.com/app-generator/django-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!

- 👉 [Dynamic API for Django](https://github.com/app-generator/django-dynamic-api) - `source code`
- 👉 [Dynamic API for Django](https://pypi.org/project/django-dynamic-api/) - `PyPi` page
- 👉 [Dynamic API for Django](https://appseed.us/developer-tools/django-dynamic-api/) - `Product Page` (for support)

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](https://www.youtube.com/watch?v=nPQMUafTrNY)

{% embed https://www.youtube.com/watch?v=nPQMUafTrNY %}

---

## ✨ Library Core Features

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

```bash
$ pip install django-dynamic-api
```

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 ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hjnlo7i3h0tvottxhs2a.png)

---

## ✨ 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](https://github.com/app-generator/core-django)

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

```bash
$ git clone https://github.com/app-generator/core-django.git
$ cd core-django
```

---

> 👉 **Step #2** - Create virtual environment and install Django

```bash
$ virtualenv env
$ source env/bin/activate
$ pip install -r requirements.txt
```

---

> 👉 **Step #3** - Migrate database

```bash
$ python manage.py makemigrations
$ python manage.py migrate
```

---

> 👉 **Step #4** - Create `SuperUser` and start the app

```bash
$ python manage.py createsuperuser 
$ python manage.py runserver
```

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

```bash
$ django-admin startapp app1
```

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.

```python
class Book(models.Model):

    title = models.CharField(max_length=100)
    info  = models.CharField(max_length=100, default='')
```

---

> 👉 **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:

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

    "app1", # <-- NEW
]
```

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

```bash
$ python manage.py makemigrations
$ python manage.py migrate
```

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](https://pypi.org/project/django-dynamic-api/)

```bash
$ pip install django-dynamic-api
```

---

> 👉 **Step #8** - Update APPs section to include the library

```python
INSTALLED_APPS = [
...
    'django_dyn_api',            # Django Dynamic API  # <-- NEW
    'rest_framework',            # Include DRF         # <-- NEW 
    'rest_framework.authtoken',  # Include DRF Auth    # <-- NEW   
...    
]
```

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

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

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ],
}
```

`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.

```bash
$ python manage.py makemigrations
$ python manage.py migrate
```

---

> 👉 **Step #10** - Update configuration

```python
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
] 
```

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

![Dynamic API Service - Usage in POSTMAN.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uo2r3rc07wbr41jy9tbs.png)

---

The full [source code](https://github.com/app-generator/core-django-dyn-api) used in this demonstration can be found on GitHub, available for curious minds as reference.  

{% embed https://github.com/app-generator/core-django-dyn-api %}

---

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

- 👉 More [Developer Tools](https://appseed.us/developer-tools/) provided by `AppSeed`
- 👉 Free [support](https://appseed.us/support/) via Email & Discord (just in case)