Sam R.
Sam R.

Reputation: 16450

Where to put REST API in Django

Here is a quote from Two Scoops of Django: Best Practices For Django 1.6:

In the past, we placed all API view code into a dedicated Django app called api or apiv1, with custom logic in some of the REST views, serializers, and more. In theory it’s a pretty good approach, but in practice it means we have logic for a particular app in more than just one location.

Our current approach is to lean on URL configuration. When building a project-wide API we write the REST views in the views.py modules, wire them into a URLConf called something like core/api.py or core/apiv1.py and include that from the project root's urls.py module. This means that we might have something like the following code:

# core/api.py

""" Called from the project root's urls.py URLConf thus:
url(r" ˆ api/", include("core.api"), namespace="api"),
"""

from django.conf.urls.defaults import patterns, url

from flavors import views as flavor_views
from users import views as user_views

urlpatterns = patterns("",
    # {% url "api:flavors" %}
    url(
        regex=r" ˆ flavors/ $ ",
        view=flavor_views.FlavorCreateReadView.as_view(),
        name="flavors"
        ),

    # {% url "api:flavors" flavor.slug %}
    url(
        regex=r" ˆ flavors/(?P<slug>[-\w]+)/ $ ",
        view=flavor_views.FlavorReadUpdateDeleteView.as_view(),
        name="flavors"
        ),

    # {% url "api:users" %}
    url(
        regex=r" ˆ users/ $ ",
        view=user_views.UserCreateReadView.as_view(),
        name="users"
        ),

    # {% url "api:users" user.slug %}
    url(
        regex=r" ˆ users/(?P<slug>[-\w]+)/ $ ",
        view=user_views.UserReadUpdateDeleteView.as_view(),
        name="users"
        ),
)

But I don't understand where to put core/api.py. Is this a separate Django app called core? Where api.py should sit?

Upvotes: 1

Views: 1575

Answers (1)

Anentropic
Anentropic

Reputation: 33903

It means create the file you have as core/api.py (along with an empty core/__init__.py file) and then add the line url(r" ˆ api/", include("core.api"), namespace="api") to the root urls.py file of your project.

You don't have to call it core/api.py, that is just a suggestion from the authors

what does we write the REST views in the views.py modules mean?

It means what you've done, for each of the Django apps in your project, such as flavors, users they will have a views.py (or views/*.py) in them where you'd put the code for both the API and non-API views. (this is just a sane naming convention, nothing more... Django relies on the urlpatterns to tell it how to connect url routes to view code)

It's great to build up stuff like this from scratch as a way to learn Django. If you're doing a serious REST API project have a look at Django REST framework.

Upvotes: 2

Related Questions