Integrate Django (Python) REST APIs

Django is an extremely popular way to quickly and securely build RESTful APIs with Python. Moesif is a great addition to your Django and Python API stack to cover everything from analytics to helping you set up metered billing.

Building your API is just the first step. Once built, you need to keep customers and services using the API happy. Moesif is the tool to help you do exactly that.

Integrating Moesif with your Django API can be done in a few simple steps. In this blog I’ll show you how to:

  • Create a Moesif Account
  • Integrate Moesif into your API code
  • Verify the integration
  • Be ready to jump into docs and get started!

Create your Moesif Account

If you don’t already have a Moesif account, You’ll want to sign up. Once you’re registered you’ll need to add in a few details.

Moesif create account first screen

These include:

  • Organization Name
  • the name of your organization or company
  • App Name
  • the name of the app you are integrating with Moesif
  • What best matches your role?
  • Here you can describe what your current role is at your organization. This helps us to assist you with relevant hints and tips in the future.
  • What are you hoping to achieve?
  • Here you can let us know how you'll use Moesif to help your organization or project.

Once you’ve filled out these details, click Next. After this, you’ll be presented with a brief overview of Moesif.

Moesif create account overview screen

Click Next once again.

Add the Moesif integration code

After the Overview screen, you’ll be presented with the Quick Install screen. Here you can pick from any different server integrations and plugins. For Django, we want to make sure Python is selected in the left pane and that the Django walkthrough is displayed on the right.

Moesif config screen with Django integration info displayed

Once selected, follow Step 1 on the screen and add the SDK to your project via pip. To do this, in your terminal (ensure that you are in your projects root directory) run the following:

pip install moesifdjango

NOTE: depending on what version of Python you are using, you may also use pip2, for version 2, or pip3 for version 3+. Check what version you are using and be consistent with your pip commands throughout the tutorial to avoid any issues.

When the command completes, the SDK will be added to your project.

Next, you’ll want to add the integration code into your app. To do this, we need to add the Moesif SDK to your middleware. Add the following line to your code in your settings.py file:

MIDDLEWARE = [
    ...
    'moesifdjango.middleware.moesif_middleware'
    ...
]

Once that line is added, you’ll need to add your Moesif middleware configuration. To do that, add the following lines to your settings.py file as well:

MOESIF_MIDDLEWARE = {
    'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID',
}

The above lines of code configure the Moesif middleware component in your Django setup. There are lots of other options you can add to the configuration, this just sticks to the basics. To learn more about configuration options for the middleware, check out our Django integration guide.

Save your code and deploy your updated API.

After adding the above code, your API will now send events through to Moesif. For reference, I have provided a simple example of my settings.py file:

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure--t(53r*3v!zspu#3@wvk(^hbhhe!7u%3b!5_6t=-3hyt00+%dw'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'moesifdjango.middleware.moesif_middleware'
]

ROOT_URLCONF = 'tutorial.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'tutorial.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10
}


# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

STATIC_URL = '/static/'

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

MOESIF_MIDDLEWARE = {
    'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID',
}

Fire off your first request

Once your API code is back up and running, it’s time to issue a request to your endpoint. My preference for this is to use Postman to send the GET request.

Regardless of how the request is sent, the Moesif integration into your application isn’t complete until the first request is sent and detected by Moesif. In the Moesif setup screen, before you send off the request, you should see a dialog at the bottom of the screen showing “No data received yet.”

Moesif no data received onboarding screen

To continue, send off the request to your endpoint.

Confirm your integration

After the request is sent, Moesif should receive the event and data. This may take a few moments for the first request to reflect in the system, once sent. Once received, Moesif will confirm that you are ready to move forward. The previous prompt will turn green and show “Data Received!”.

Moesif data received onboarding screen

Lastly, scroll to the bottom of the screen and click Next.

Moesif next button

Invite your team

The final step in the setup is to invite your team. The next screen is where you can do this quickly and easily.

Moesif invite team screen

If you’d like to add a team member, simply add their email and click Send Invite.If you don’t have any team members yet or want to skip this step, you can always add team members later.

Once you’ve added all the team members you want, click Finish.

Explore Moesif!

You’ve now successfully integrated your API application with Moesif. You should now see the Moesif dashboard in the browser, ready to explore.

Moesif dashboard with event received

Now that your API is integrated and moving data into Moesif you can start to explore. Check out our docs to find everything from API analytics, monitoring and alerts, and more!

Updated: