Skip to content

Instantly share code, notes, and snippets.

@zincsoda
Last active April 8, 2017 20:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zincsoda/fa23970e0ca174ada985 to your computer and use it in GitHub Desktop.
Save zincsoda/fa23970e0ca174ada985 to your computer and use it in GitHub Desktop.
How to create django REST API in less than 20 minutes

1. Set up a python virtual enviornment

a. install virtualenv

sudo easy_install pip
sudo pip install setuptools --no-use-wheel --upgrade
sudo pip install virtualenv
sudo pip install virtualenvwrapper
cd $HOME
mkdir .virtualenvs
echo "source /usr/local/bin/virtualenvwrapper.sh" >> ~/.bash_profile
. /usr/local/bin/virtualenvwrapper.sh

b. create a virutal env

mkvirtualenv <your_env_name>
pip install django

2. Create a empty django project

django-admin.py startproject --template=https://github.com/zincsoda/heroku-django-template/archive/master.zip --name=Procfile meetups

3. Install requirements.txt dependencies

pip install -r requirements.txt

4. Create the database

./manage.py syncdb

5. Run the webserver

./manage.py runserver 0.0.0.0:5005

6. Install the new app

Open meetups/settings.py and add 'meetups' to INSTALLED_APPS

7. Create a views module

Create meetups/views.py and add the following lines:

from django.http import HttpResponse

def test(request):
    return HttpResponse("Hello WWCode")
    

8. Create a url to simple view

Open urls.py.

Import our newly created view module

import meetups2.views

Add the line to the urls tuple:

url(r'^test$','meetups2.views.test'),

9. Return JSON data

In views.py, add a python dictionary of users and return a json response instead. Change the file as follows:

from django.http import HttpResponse
import json

def test(request):

    my_dict = {'users': ['bob','mary','kate']}
    json_data = json.dumps(my_dict)
    return HttpResponse(my_dict)
    return HttpResponse(json_data, content_type="application/json")
   

10. Create a models module

Create a file called meetups/models.py with the following contents:

from django.db import models

class Image(models.Model):
    name = models.CharField(max_length=200, blank=True, null=True)
    image_url = models.CharField(max_length=1000, blank=True, null=True)

    def __unicode__(self):
        return self.name


class Meetup(models.Model):
    name = models.CharField(max_length=200, blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    meeting_time = models.CharField(max_length=200, blank=True, null=True)
    location = models.CharField(max_length=200, blank=True, null=True)
    postcode = models.CharField(max_length=12, blank=True, null=True)
    contact = models.CharField(max_length=200, blank=True, null=True)
    image = models.ForeignKey(Image, blank=True, null=True, on_delete=models.SET_NULL)
    website = models.CharField(max_length=500, blank=True, null=True)

    def __unicode__(self):
        return self.name


11. Show these models in the database

Run:

./manage.py migrate

Open up db.sqlite3 and show the tables we have created.

12. Set up the Django Admin Console

Create a file meetups/admin.py

from django.contrib import admin
from models import *

class MeetupAdmin(admin.ModelAdmin):
    list_display = ('name','description', 'contact', 'location')
admin.site.register(Meetup, MeetupAdmin)

class ImageAdmin(admin.ModelAdmin):
    list_display = ('name','image_url',)
admin.site.register(Image, ImageAdmin)

13. Now, we install the django rest framework

Install the django rest framework:

pip install djangorestframework

Add 'rest_framework' to INSTALLED_APPS

14. Create a serializer module

Create a file called meetsup/serialzers.py and add the following content:

from rest_framework import serializers
from meetups2.models import *


class ImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Image
        fields = ('id','image_url')

class MeetupSerializer(serializers.ModelSerializer):

    image_url = serializers.CharField(source='image.image_url', read_only=True)

    class Meta:
        model = Meetup
        fields = ('id','name','description','meeting_time','location','postcode','contact','image_url')
        

#15. Create Mixin classes for Meetups

In views.py, add the following headers

from meetups2.models import Meetup
from meetups2.serializers import MeetupSerializer
from rest_framework import generics

Then add the following classes:

class MeetupList(generics.ListCreateAPIView):
    queryset = Meetup.objects.all()
    serializer_class = MeetupSerializer

class MeetupDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Meetup.objects.all()
    serializer_class = MeetupSerializer

16. Add a url for each class view

Open urls.py, add the follwing import to

from rest_framework.urlpatterns import format_suffix_patterns

Add this code to end of urls.py

urlpatterns = format_suffix_patterns(urlpatterns)

Then add the following lines to the url dispatcher tuple:

url(r'^meetups$', views.MeetupList.as_view(), name='meetup-list'),
url(r'^meetups/(?P<pk>[0-9]+)$', views.MeetupDetail.as_view(), name='meetup-detail'),

17. Enjoy

/meetups will now show you the lovely Django REST Frameworks UI for interacting with your models through REST

#18. Push to Heroku

Capture all new python dependencies in the requirements file:

pip freeze > requirements.txt

You may need to first install heroku toolbelt. Then type the following command:

heroku create

This will create a heroku app with a generated name. It will also set up your git repository with a new remote for heroku so that you can now just push your repo to heroku using the following command:

git push heroku master

Remember that you need to initialize your new heroku database:

heroku run python manage.py syncdb

Navigate to the URL and it should be working.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment