Dynamic API

Dynamic API#

This page explains how to use the Dynamic API feature of Dynamic Django that allows to expose API endpoints for any model without coding.

👉 New to App-Generator? Sign IN with GitHub or Generate Web Apps in no time (free service).

Configuration#

The django_dyn_api, the application that handles the feature, is registered in the INSTALLED_APPS section. djangorestframework package being a core dependency, is also registered:

core/settings.py#
INSTALLED_APPS = [
    ...
    "django_dyn_api",
    ...
    "rest_framework",
    "rest_framework.authtoken",
    ...
]

The DRF Library has a distinct section that configure the authentication layer:

core/settings.py#
REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "rest_framework.authentication.SessionAuthentication",
        "rest_framework.authentication.TokenAuthentication",
    ],
}

Dynamic API section (also covered in the configuration page) provides a simple way to specify the models that are automatically managed.

The section is a dictionary where the key is the segment of the endpoint and the value the import path of the model. Here are the DEMOs for the default models:

core/settings.py#
# Syntax: URI -> Import_PATH
DYNAMIC_API = {
    "product": "home.models.Product",
    "sales": "home.models.Sales",
}

Add a new Model#

Besides the default API endpoints, the Dynamic API feature can be extended to any new model. Here are the steps to enable a new endpoint

  • Define a new model Homework in the home aplication

home/models.py#
class Homework(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=100)
    content = models.TextField(blank=True, null=True, default='')
  • Migrate the database

python manage.py makemigrations
python manage.py migrate
  • Update the configuration: DYNAMIC_API section

core/settings.py#
# Syntax: URI -> Import_PATH
DYNAMIC_API = {
    "product": "home.models.Product",
    "sales": "home.models.Sales",
    "homework": "home.models.Homework",  # <-- NEW
}
  • The new endpoint is now listed in the Dynamic API and ready to be used.

Dynamic API - New endpoint registered
  • The new DRF Endpoint

Dynamic API - New endpoint DRF view