Skip to content

Instantly share code, notes, and snippets.

@vijayanandrp
Last active January 25, 2017 11:17
Show Gist options
  • Save vijayanandrp/ecd5298411fe57b7d7ce7f563a688675 to your computer and use it in GitHub Desktop.
Save vijayanandrp/ecd5298411fe57b7d7ce7f563a688675 to your computer and use it in GitHub Desktop.
REST API - Django

Django - REST API - for development [Blue Print]

(Version used - Django 1.10.2) in 10 steps

Before start developing make sure you have installed djangorestframework. I have used pycharm professional edition to learn and practice.

pip3.5 install djangorestframework
  1. Create a new web project under the Django in Pycharm IDE. Say Example, website
  2. Run manage.py (Tools -> Run manage.py task)
  3. create the startapp. Say Example, websiteAPI
python manage.py startapp companies
  1. Now, its time to register rest-framework and comapanies in settings.py (under website path) to make sure Django knows that this application gonna be REST API

    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'rest_framework',
        'companies.apps.CompaniesConfig'
    ]
  2. companies -> models.py (Create models to store and send the data when needed)

    from django.db import models
    
    
    class Stock(models.Model):
        ticker = models.CharField(max_length=10)
        open = models.FloatField()
        close = models.FloatField()
        volume = models.IntegerField()
    
        def __str__(self):
            return self.ticker
  3. companies -> admin.py (Update models info in admin file)

    from django.contrib import admin
    from .models import Stock
    
    admin.site.register(Stock)
  4. Run manage.py (Tools -> Run manage.py task)

  • makemigrations to update the table structure
python manage.py makemigrations
  • migrate
python manage.py migrate
  • createsuperuser
python manage.py createsuperuser
  1. Run the project. [http://127.0.0.1:8000/admin/]
  • type the user name and password to update stocks manually
  1. Create the serializers.py under companies directory. (converting model into JSON object. Serializers means saving the data in a format you can transmit)
from rest_framework import serializers
from .models import Stock


class StockSerializer(serializers.ModelSerializer):
  
  class Meta:
      model = Stock
      # fields = ('ticker', 'volume')
      fields = '__all__'
  1. update the views.py under companies directory.
from django.shortcuts import get_object_or_404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import Stock
from .serializers import StockSerializer

# List of stocks or create a new one
# stocks/
class StockList(APIView):
  
  def get(self, request):
      stocks = Stock.objects.all()
      serializer = StockSerializer(stocks, many=True)
      return Response(serializer.data)
  
  def post(self):
      pass
  

  ```   
10. update the **urls.py** under website directory (main project). 
```python
from django.conf.urls import url
from django.contrib import admin
from rest_framework.urlpatterns import format_suffix_patterns
from companies import views


urlpatterns = [
  url(r'^admin/', admin.site.urls),
  url(r'^stocks/', views.StockList.as_view()),
]

urlpatterns = format_suffix_patterns(urlpatterns)
  ```   

Finally run [http://127.0.0.1:8000/stocks/] is your browser. You will get the stocks list as a JSON
@vijayanandrp
Copy link
Author

[[Credits: ]https://www.youtube.com/playlist?list=PL6gx4Cwl9DGBlmzzFcLgDhKTTfNLfX1IK] I gained these knowledge from here.

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