In this article, I'm gonna create REST APIs in the Django framework more likely in Django-rest-framework. What I discovered while learning Django is Robust Framework and I sound like "WoW". how, ... wait let's create and I bet you that you will sound the same as I did.
make sure you've already installed python3.8+, now let's create an isolated environment for our project so it won't hurt our OS. you can install
pipenv through your OS package manager like
brew or you can do it through the
Boom, we're inside the virtual environmental, if you see parentheses in your command. we should start out by creating the Django traditional project named
todo_project and adding the
todos app (App is where we create all our code) and migrating our initial database
In Django, we always need to add a new app inside
INSTALLED_APPS. to do so, open up
todo/todo_project/settings.py and add at the bottom.
# todo_project/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Local 'todos', # new app added here ]
head over to
http://127.0.0.1:8000/ And Boom There you have your first Django project, Awesome. Now let's create a Model; Model is where we create our Database Structure (same is Scheme in NodeJS).
open up your model file
# todo/todos/models.py from django.db import models class Todo(models.Model): title = models.CharField(max_length=250) body = models.TextField() def __str__(self): return self.title
first, we import the
models then we created
body for our Todo-app.
CharField is character with max_length,
TextField is text (suppose it like
textarea in HTML). we have to add
Field at the end of everything like
BooleanField(). and the
__str__ return the title when you instance the model.
Now Register the Todo model in the admin
# todo/todos/admin.py from django.contrib import admin from .models import Todo # Register your models here. class TodoAdmin(admin.ModelAdmin): list_display = ('title', 'body') admin.site.register(Todo, TodoAdmin)
list_display will give us the
body on the admin page in the column, more user-friendly. migrate the charges, every time we made some changes in the model. we have to migrate
It's time to install the Django-rest-framework for APIS and CORS lib for CORS problem:
# todo_project/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # 3rd party 'rest_framework', # new added 'corsheaders', # new added # Local 'todos', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', # new added 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]
and allow the URLs to make a request for the backend and frontend
# new CORS_ORIGIN_WHITELIST = ( 'http://localhost:3000', 'http://localhost:8000', )
The next step is to Configure URL for our API endpoints in
# todo_project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('todos.urls')) ]
todos.urls file, we yet have to create, so let's create
todos/urls.py and add these line:
# todos/urls.py from django.urls import path from .views import ListTodo, DetailTodo, CreateTodo urlpatterns = [ path('<int:pk>/', DetailTodo.as_view()), path('', ListTodo.as_view()), path('create', CreateTodo.as_view()) ]
we imported the
ListTodo, DetailTodo and
CreateTodo which we yet have to create these classes. and
urlspatterns is where we create our routs.
<int:pk> is passing the Primary key as a URL query.
we need a serializer file to transpile the python queryset to JSON in order to send it over HTTP request. let's go ahead and create a file
from rest_framework import serializers from .models import Todo class TodoSerializer(serializers.ModelSerializer): class Meta: model = Todo fields = ('id', 'title', 'body')
Importing the Todo Model and exposing the
id, title, body field as JSON in the
model variable is which model we need to transpile and fields is which fields we need to expose.
id field is created automatically when adding new object
todos/views.py file and the logic
from rest_framework import generics from .serializers import TodoSerializer from .models import Todo # Showing the List class ListTodo(generics.ListAPIView): queryset = Todo.objects.all() serializer_class = TodoSerializer # fetching single todo class DetailTodo(generics.RetrieveAPIView): queryset = Todo.objects.all() serializer_class = TodoSerializer # creating one class CreateTodo(generics.CreateAPIView): queryset = Todo.objects.all() serializer_class = TodoSerializer
now run the server and head over to 'http://127.0.0.1:8000/api/create`
it will let you create a new todo, and play around with. isn't it cool! we didn't create any logic to create a new todo. this is how it wins. to read more about generics Github Repo: https://github.com/lifeeric/django-rest-api/
Thanks for following along with me, if you found any error, mistake, please fix me I'll be happy!
if you found something for me, let do it together!