Hello, My name is Hiro.
I am a student of web development in Vancouver.
In this time, I tried creating my own API with Django.
This article just shows how to create a simple api. It means that we can just get all data. But, this is useful and we can get knowledge about API by creating it by ourselves.
I will show you how to build your own API with Django Rest Framework. This library helps you create it easily.
Don't worry, it is not important if you know about python or django. I will show it with command line base.
Let's try to create your API!
Check python environment
At first, we check whether python is installed or not.
If not, you can install it from here. We should use python with more than 3.0 version.
Download python
python -v or python3 -v
pip -v or pip3 -v
Note: If the command doesn't work, you can check your PATH environment.
Install virtualenv
We can create a virtual environment for this time because we should separate the python environment each project.
pip install virtualenv
Create virtualenv
After install virtualenv, we can use virtualenv command.
If you do not use it, please check PATH environment.
virtualenv {eivironment_name}
Next, activate virtual environment.
source {eivironment_name}/bin/activate
Create django project
After activating virtual environment, we install django.
pip install django.
Next step, we create django project.
django-admin startproject {Project_name}
Move to project folder
cd {Project_name}
Create django application
We can create django application like this command.
django-admin startapp {App_name}
We finished initial setup! Next, We will check the default django admin app.
1. Check django admin
You can register your username and password after createsuperuser command.
python manage.py migrate
python manage.py createsuperuser
After that, you can run development server.
python manage.py runserver
We can access the development server and admin app!
Login by using your username and password before you register.
2. Display Hello world
Next step, We try to displaying "Hello Django".
At first, we modify views.py in our app folder. Views.py can return HTTP Response, Json and so on. We can define what response we can see here.
Note: app folder means we create the folder with python manage.py startapp command
# {app_folder}/views.py
from django.http import HttpResponse
def Top(request):
return HttpResponse("<h1>Hello Django</h1>")
Second, we create new urls.py in our app folder.
We can define what url path connect the response in views.py.
In this case, http://localhost:8000/ can connect Top in View.py and get HTTP Response.
# {app_folder}/urls.py
from django.urls import path
from .views import Top
urlpatterns = [
path('', Top), # http://localhost:8000/
]
Finaly, we edit urls.py in PROJECT folder.
This project urls.py can be connected to our app's urls.py.
Note: project folder means we create the folder with python manage.py startproject command
And, edit the file like this.
# {project_folder}/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls), # http://localhost:8000/admin
path('', include('{your_app_name}.urls')), # http://localhost:8000/
]
Now, we can see "Hello Django" after running our development server.
3. Modify models.py and Register admin app
After we can see "Hello Django", we modify models.py.
We can update like this.
# {app_folder}/models.py
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=50)
description = models.CharField(max_length=100)
def __str__(self):
return self.name
Models.py can define our database table and columns. In this case, I define product table and name and description fields but you can define anythings. CharField means Character Fields. We do not have to write SQL syntax.
Next step, we will use this model for creating our database.
We can use this commnad.
python manage.py makemigrations
Automatically generate 0001_initial.py file in migrations folder.
Next, we execute this command.
python manage.py migrate
Finaly, We register the model to admin app. We can edit admin.py in app folder like this.
# {app_folder}/admin.py
from django.contrib import admin
from .models import Product # import our model
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
pass
And then, we can see the model in admin app after we login our admin app!
We can add some data from admin app now.
4. Setup Rest Framework
Next, we will install Django Rest Framework.
pip install djangorestframework
And, add the app to the project settings.py like this.
INSTALLED_APPS = [
...
'rest_framework',
]
And then, edit the views.py.
INSTALLED_APPS = [
...
'rest_framework',
]
In this time, we create serializers.py in app folder.
This serializer helps us to communicate data between models and python.
We can write like this.
# {app_folder}/serializers.py
from rest_framework import serializers
from .models import Product
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = '__all__'
We can also modify the views.py like this.
# {app_folder}/views.py
from django.http import HttpResponse
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import Product
from .serializers import ProductSerializer
# Create your views here.
def Top(request):
return HttpResponse("<h1>Hello Django</h1>")
# ---New---
@api_view(['GET'])
def getAllProducts(request):
products = Product.objects.all() # Get all data
serializer = ProductSerializer(products, many=True) # Data Converter
return Response(serializer.data)
Finaly, we can modify urls.py in app folder like this.
from django.urls import path
from .views import Top, apiOverviews, getAllProducts
urlpatterns = [
path('', Top), # http://localhost:8000
path('api/products/', getAllProducts), # http://localhost:8000/api/products
]
Path: api/products is up to you. we can write any path.
After you register your own data from admin app, you can check the data from api/products.
http://localhost:8000/api/products
Conclusion
In this article, we just created api function of get all data on local environment. I will create the article about deploying this simple api into real world with Heroku.
Of course, if you are curious about other api functions like specific GET, POST, PUT and DELETE, I can write more article.
If you interested in this article, please comment to me!
Thank you for taking your time to read this article!
Biography
I am student of Vancouver, Canada and have job experience for Back-end technology. I also like AWS services and have some certifications.
Nowadays, I am learning Front-end Technology like JavaScript/TypeScript, React, Next.js.
I am looking for part-time job or volunteer work in Canada. If you are curious about me, Please contact me😸
Top comments (0)