It is getting extremely hard now to go online and not see a reference to an API. A lot of you just starting out with development don’t know what an API is or why it is so important. Hopefully this article will help you get started.
API (Application Program Interface) is a medium that allows software to talk to other softwares. Let’s say you want to get some data out of a site like IMDB. If there were no api, then you’d have to go to the site and manually scrape the data which is extremely complicated. Now suppose there is an api, so now all you have to do is make a request and get the data. An API helps the developer think less about getting the data and spend more time on actual development.
Now let’s say you have a database and you want to get some data out of it. What you do is, you make an api that has access to the database. Just make it using Django. Then make an API endpoint which, even requested, will give out the data you have in your database. I will be going over exactly how to do this in Django.
For this tutorial, you need to have the basics, know how to use the command terminal, have virtual environment installed, have basic preliminary understanding of Django. If you don’t, then don’t worry I am linking all the tutorials I personally prefer.
Now that you have everything installed or at least know the workflow, lets start coding.
I like to keep my projects organized, so, I start with creating a folder in documents or on my desktop.
This will create a folder called django-api-tutorial
You will enter the folder you just made
This will create a virtual environment. Imagine virtual environment as an environment for your specific project. If you don’t have it, then you would have to install all the packages on the global environment. Now there’s nothing wrong with that but soon you will have multiple projects on your computer. When you do that, different projects might use different versions of Django or any other packages. That’s when you will start facing problems because versioning really matters in Django. An old project might have an old version of Pillow (to handle images) while a new project might have a new version of Pillow. Things like these would cause problems which is solved by making the project in a virtual environment. If you want to see how many packages you have installed in your virtual environment type the command pip freeze or pip list.
Now that you have your virtual environment, turn it on.
Now install Django in your virtual environment
pip install django
Pip is your package installing library. All it does is, it installs whichever package you want. its very convenient and it will always download the most updated version of the package you want unless you specifically write the version number, pip install django==1.9.
Now if you write command pip free or pip list, you can see which version of Django you have in your virtual environment. Don’t freak out if you see pytz or setuptools right after Django. Sometimes a few more packages get installed with Django because they help it to run.
Now write command
django-admin startproject restApi
This will create a folder which will contain all the files you need to have a Django app.
Now you can enter the folder and write commands
python manage.py migratepython manage.py createsuperuser
These were the basics, now comes the fun part.
Install Django Rest Framework
pip install djangorestframework
pip install markdown
pip install django-filter
With these commands, Django Rest Framework will be installed and the other packages are needed for making the webpage from where you can send different requests to your application. You will see them as soon as we finish.
Enter ‘rest_framework’ under INSTALLED_APPS inside settings.py. These instructions are also available in the Django documentation.
Now open the project in your most preferred text editor. I prefer using sublime text or atom. We will make an app in the project.
python manage.py startapp data
What this does is, it creates a folder called data containing the basic things you need to be routed to that folder and make schemas and views. Basically creating an app creates some boilerplate codes which you need or else you would have to write them yourself and it gets repetitive.
Enter the name of your app to your settings.py file.
Inside the data folder, there will be a models.py file. You have to open the file and make a schema for a database.
name = models.CharField(max_length=120, null=True, blank=True)
number = models.IntegerField(null=True, blank=True) def __str__(self):
This is the most simplest schema I can think of.
python manage.py makemigrations
python manage.py migrate
This would generate the database.
Now in admin.py, enter
From .models import data
This would import the data model and show it in the admin panel.
Now run python manage.py runserver and go the admin panel, it will have data in it. Now enter some sample data.
Go back to your text editor, inside the data folder, make a file called urls.py and another called serializers.py.
Here’s a quora question on why we need to have serializers. also, don’t forget to read up on the documentation. Basically what serializer does is, it decreases a lot of the code which otherwise you’d have to write to get the data.
Inside the serializer file, write this:
from rest_framework import serializers
from .models import dataclass dataSerializer(serializers.ModelSerializer):
model = data
fields = ('__all__')
Checkout the documentation to find out more about it. We used a modelserializer which helped us not write a lot of code.
Now in the views, write this
from .serializers import dataSerializer
from .models import data
from rest_framework import generics
# Create your views here.class dataList(generics.ListCreateAPIView):
queryset = data.objects.all()
serializer_class = dataSerializerclass dataDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = data.objects.all()
serializer_class = dataSerializer
These class based views are also explained here.
All we have left now is routing the Django app to these views. Go to the urls.py file in the restApi folder and enter this line
You have to import ‘include’, just write it after ‘from django.conf.urls import url’.
Inside the urls.py file in data folder, enter
from django.conf.urls import url, include
from .views import dataList, dataDetailurlpatterns = [
# url(r'^admin/', admin.site.urls),
The ‘$’ sign means end of line. so, if you go to url http://127.0.0.1:8000/, you will go to dataList view. Which will return the list of all the items present in the database.
(?P<pk>\d+) is a regex that accepts numbers (the primary key of the items). So if you go to url http://127.0.0.1:8000/2 you will be able to see the item in primary key=2.
Now if you have no errors on your command terminal, run the application and go to your browser and go to url http://127.0.0.1:8000/. If all worked well, you will see this.
This is a very basic application in Django Rest Framework. You can also perform POST, PUT, DELETE actions on this. The demo for this project is available on my github. Now you can build an application using ReactJs or AngularJs or Android app and get data out of this application to show in your frontend. You can try out ngrock if you want to share this application to your friends or want to try it yourself.
Please leave a comment if you find any mistakes or if you are unclear on anything or if you have any suggestions.