Skip to content

Creating a REST service API with Django and Django Rest Framework

Rodrigo Ancavil del Pino edited this page Mar 27, 2014 · 7 revisions

Resume

We will create an API to expose a django model through an Rest service. Our model will be a Message with the fields: author, text and timestamp. We'll be able to access to the model with the next URL.

 http://$your-app-$yournamespace.rhcloud.com/api/message

Install the djangorestframework in Django

Put djangorestframework in the install_required in setup.py

setup(name='YourAppName', version='1.0',
       description='OpenShift Python-3.3 / Django-1.6 Community Cartridge based application',
       author='Your Name', author_email='[email protected]',
       url='https://pypi.python.org/pypi',

       #  Uncomment one or more lines below in the install_requires section
       #  for the specific client drivers/modules your application needs.
       install_requires=['Django<=1.6',
		     'static3',  # If you want serve the static files in the same server
		     'djangorestframework',
                         #  'mysql-connector-python',
                         #  'pymongo',
                         #  'psycopg2',
        ],
 )

We will return to this later...

First, we need to create and configure the service.

First, creating the rest api service (the code)

Create the api services for django (using manage.py script).

 cd wsgi/openshift
 python manage.py startapp services
 cd services

You create the next directory structure.

 services/
      __init__.py
      views.py
      models.py
      tests.py

Go to the service directory

 cd services

Create the model. Edit the file models.py (located in services directory) and write and save the code.

 from django.db import models
 # Create your models here.
 class Message(models.Model):
      author = models.CharField(max_length=20)
      text = models.CharField(max_length=140)
      timestamp = models.DateTimeField(auto_now_add=True)

      def __unicode__(self):
          return self.author

Create the admin.py file (in the same directory of models.py), for administrate the model througth the Django admin console.

 from django.contrib import admin
 from .models import Message

 class MessageAdmin(admin.ModelAdmin):
     list_display = ('author','text', 'timestamp')
        
 admin.site.register(Message, MessageAdmin)

Create the serializer.py file (in the same directory of models.py).

 from rest_framework import serializers
 from .models import Message

 class MessageSerializer(serializers.HyperlinkedModelSerializer):
      class Meta:
           model = Message
           fields = ('author','text','timestamp',)

Create the views for the service. For this edit the views.py file.

 # Create your views here.

 from .models import Message
 from rest_framework import viewsets
 from .serializer import MessageSerializer

 class MessageViewSet(viewsets.ReadOnlyModelViewSet):
      queryset = Message.objects.all()
      serializer_class = MessageSerializer

Note: With viewsets.ReadOnlyModelViewSet we create the API on read only mode. In other words, we can to use GET only.

Config the urls. Edit the urls.py file (located in wsgi/openshift)

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

 # Uncomment the next two lines to enable the admin:
 from django.contrib import admin
 admin.autodiscover()

 from rest_framework import routers
 from services.views import MessageViewSet

 router = routers.DefaultRouter(trailing_slash=False)
 router.register(r'message', MessageViewSet)

 urlpatterns = patterns('',
       # Examples:
       url(r'^$', 'views.home', name='home'),
       # url(r'^$', 'openshift.views.home', name='home'),
       # url(r'^blog/', include('blog.urls')),
 
       url(r'^admin/', include(admin.site.urls)),

       url(r'^api/',include(router.urls)),
       url(r'^api-auth/',include('rest_framework.urls', namespace='rest_framework')),
  )

Second, install the djangorestframework and the api service

Go to the directory wsgi/openshift and edit the settings.py file, and install the app (services) and the djangorestframework.

 INSTALLED_APPS = (
	'django.contrib.admin',
	'django.contrib.auth',
	'django.contrib.contenttypes',
	'django.contrib.sessions',
	'django.contrib.messages',
	'django.contrib.staticfiles',
	'rest_framework',
	'services',
)

Third, update the git repository on OpenShift

  git add .
  git commit -am"installing the djangorestframework and the services rest api"
  git push

git push going to run setup.py, which will install djangorestframework in our OpenShift account. To then install our Rest API (services).

Finally, test the api

Go to django web admin console, and go to the model Message.

http://$your-app-$yournamespace.rhcloud.com/admin

Add one register.

Save it....

And go to the api rest.

http://$your-app-$yournamespace.rhcloud.com/api

You can see a real example here