Skip to content

Instantly share code, notes, and snippets.

@scottie
Last active September 19, 2023 17:55
Show Gist options
  • Save scottie/d5688c9fa9ceecedef41621cb10ad237 to your computer and use it in GitHub Desktop.
Save scottie/d5688c9fa9ceecedef41621cb10ad237 to your computer and use it in GitHub Desktop.
django-rest-framework-starter

First install django and DRF:

pip3 install django djangorestframework

Step 1: Make a project and an app.

django-admin startproject projectname .
django-admin startapp apiname

Step 2: Add INSTALLED_APPS in the project's settings.py file.

- Navigate to project settings.py and scroll down to INSTALLED_APPS
- Add "api name".apps.ApiConfig and rest_framework to the INSTALLED_APPS.

Also to settings.py add the below for later docker generation:

import os
# Set the STATIC_ROOT to a valid filesystem path
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

Step 3: Create models in the API app (apiname/models.py):

from django.db import models

class Location(models.Model):
    locationName = models.CharField(max_length=100, unique=True)

    def __str__(self):
        return self.locationName

class Item(models.Model):
    itemName = models.CharField(max_length=100)
    date_added = models.DateField(auto_now_add=True)
    itemLocation = models.ForeignKey(Location, on_delete=models.CASCADE)

    def __str__(self):
        return self.itemName

Step 4: Register models in the admin.py file of the API app (apiname/admin.py):

from django.contrib import admin
from .models import Item, Location

admin.site.register(Item)
admin.site.register(Location)

Step 5: Perform migrations, create a superuser, and run the server.

python3 manage.py makemigrations
python3 manage.py migrate
python3 manage.py createsuperuser
python3 manage.py runserver

Step 6: Create URL patterns and serializer files.

touch api/urls.py #create api/Urls.py
touch api/serializer.py #Create serializer djangorestframework uses this to convert the data to json
  • In the project's urls.py, add URL patterns:
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('apiname.urls')),  # Replace 'apiname' with your app's name
]

Step 6 (Continued): Edit the app's urls.py file (apiname/urls.py):

from django.urls import path
#from .views import ItemList, ItemDetail, LocationList, LocationDetail

urlpatterns = [
    #path('item/', ItemList.as_view()),
    #path('item/<int:pk>/', ItemDetail.as_view()),
    #path('location/', LocationList.as_view()),
    #path('location/<int:pk>/', LocationDetail.as_view()),
]

Uncomment the above # once confirmed working and views are made.

Step 7 (Continued): Create or edit the serializers file (apiname/serializers.py):

from rest_framework import serializers
from .models import Item, Location

class ItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item
        fields = '__all__'

class LocationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Location
        fields = '__all__'

Step 8: Create views in the app's views.py file (apiname/views.py):

# from rest_framework.decorators import api_view
# from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework import generics  # Using class based views
from rest_framework.views import APIView
from .models import Item, Task
from .serializer import ItemSerializer, TaskSerializer
from datetime import datetime
import time
import os

# using function based view


def get_uptime():
    """
    Returns the current uptime.
    """
    # Get the timestamp when the application was started
    started_at = datetime.fromtimestamp(os.path.getctime(__file__))

    # Calculate the current uptime
    current_time = datetime.now()
    uptime = current_time - started_at

    return uptime

# @api_view(['GET'])
#  def apiOverview(request):
#    res = {
#        "success": True
#    }

#    return Response(res)

# Using generic class based views


class StatusView(APIView):
    def get(self, request, format=None):
        data = {
            "Status": True,
            "DateTime": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            "TimeStamp": int(time.time()),
            "UpTime": get_uptime()
        }
        return Response(data)


class ItemList(generics.ListCreateAPIView):
    serializer_class = ItemSerializer

    def get_queryset(self):
        queryset = Item.objects.all()
        location = self.request.query_params.get('location')
        if location is not None:
            queryset = queryset.filter(itemLocation=location)
        return queryset

class ItemDetail(generics.RetrieveUpdateDestroyAPIView):
    serializer_class = ItemSerializer
    queryset = Item.objects.all()

class LocationList(generics.ListCreateAPIView):
    serializer_class = LocationSerializer
    queryset = Location.objects.all()

class LocationDetail(generics.RetrieveUpdateDestroyAPIView):
    serializer_class = LocationSerializer
    queryset = Location.objects.all()

If the code editor can not see "rest_framework" in VSCODE press CTR + SHIFT + P and then type python:select interperator and choose your virtual enviroment.

Now, you have a complete setup that includes serializers, URL patterns, and views for your Django REST framework API. Don't forget to run the server to test your API endpoints:

python3 manage.py runserver

You can access your API at URLs like /api/item/, /api/item/<int:pk>/, /api/location/, and /api/location/<int:pk>/.

Now, you should be able to access your API endpoints, such as /api/item/, /api/location/, and perform CRUD operations.

-Check /api/item
-Add locations in /api/location/
-Check /api/location/ID(1)
-Add /api/item
-Check /api/item/?location=1
@tobiolusa
Copy link

This is a very lucid and simple boilerplate

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