Using DRF and django-tenants together in the same project

304 views Asked by At

I'm currently building a multi tenancy app with django-tenants.

However I also want to run my REST API in the same project as django-tenants.

This is where the problem arises, if I were to make my API a shared tenants app every tenant subdomain ends up having their own API.

For example, all registered tenants adopt the API routes as part of their subdomain:

tenant1.example.com/api, tenant2.example.com/api, etc.

I don't want my API to be underneath each tenant, I want to just run it on one domain, preferably api.example.com

Does anyone have any advice on how to set this up? How are other people handling this in their projects?

1

There are 1 answers

1
Shayan On

When dealing with multi-tenancy in Django with a shared API, you need to carefully structure your URL routing and configure your Django project to handle the multi-tenancy at the URL level.

Here's a general approach to achieve this:

  1. Separate API URLs from Tenant URLs:

    • Create a dedicated api app within your Django project.
    • Define your API views, serializers, and any other components within this app.
  2. Use a Single API Subdomain:

    • Configure your API to run under a single subdomain, for example, api.example.com.
    • Define the API routes in the api app's urls.py.
  3. Configure Django-Tenants:

    • Use Django-Tenants for multi-tenancy, but configure it to only consider subdomains for tenant identification.
    • Update your TENANT_URLCONFS setting to include the api app's URL configuration.

Here's an example of how your urls.py in the api app might look:

# api/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('some-endpoint/', views.SomeAPIView.as_view(), name='some-endpoint'),
    # Add more API routes as needed
]

Then, in your main project's urls.py, include the API routes and configure Django-Tenants:

# project/urls.py
from django.contrib import admin
from django.urls import include, path
from tenants import urls as tenant_urls
from api import urls as api_urls

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include(api_urls)),  # API routes
    path('tenants/', include(tenant_urls)),  # Tenant-specific routes managed by Django-Tenants
]

This way, the API routes are separate from tenant-specific routes, and the API runs under a dedicated subdomain (api.example.com).

Ensure that you configure your Django-Tenants settings appropriately and make adjustments to suit your specific requirements. Pay attention to the order of inclusion of URLs to avoid conflicts and ensure that the API routes take precedence over tenant-specific routes.