Introduce
In the context of web development, we often talk about RESTful API. This is a popular way to provide applications to third parties (applications and web). This only needs to provide information stored in the database in a common format like XML or JSON, in which a third-party application can interact with the data without having to connect directly to the database. The database, therefore, does not matter if the database is MySQL or PostgreSQL, or if the application is written in Java or Python, but RESTful APIs can be used to repair the database.
The Django REST framework is a powerful tool in building WebAPI. Some reasons when we should use REST:
- There is ORM and non-ORM data support with Serialization.
- Rich documentation, large support community.
- Used in international companies like Mozilla, Red Hat, Heroku.
Setting
1.Django and Django REST framework
We use the following statements:
1 2 3 | pip install django django -admin --vesion // check phiên bản đã cài đặt |
Then we create a folder containing application:
1 2 3 4 | mkdir TodosProject cd TodosProject django-admin startproject todos |
Next install Django REST framework:
1 2 | pip install djangorestframework |
And install and connect Django with Postgres, we follow the following article: https://viblo.asia/p/ket-noi-django-va-postgresql-nhu-the-nao-4P856NDa5Y3 . Thus we temporarily have all the necessary tools. Now is Chien !!!
Perform
In the newly created Django folder, the structure is as follows: The specific components are as follows:
- admin.py : The config file is in the admin page of the app.
- models.py : Where to create data, fields, tables.
- test.py : File unit test.
- views.py : Query data from the model. First of all like that.
1. Models
For simplicity we try to create a models.py as follows:
We understand in the model class is the table name whose properties are the data fields we want to create in PostgresSQL. With the admin.py file, we will have the attribute list we have declared in the models.py file:
File app.py :
We create an api folder including serializers.py and viewset.py. These are the 2 files we will code manipulate to create the API.
In the file serializers.py is as follows:
1 2 3 4 5 6 7 8 | from rest_framework import serializers from todos.models import Company class CompanySerialiser(serializers.HyperlinkedModelSerializer): class Meta: model = Company fields = ('_id', 'name', 'age', 'adress', 'salary', 'join_date') |
FIle viewset.py as follows:
1 2 3 4 5 6 7 8 9 | from django.http import JsonResponse from todos.models import Company def getJson(request): obj = Company.objects.all() data = { "result" :list(obj.values("_id", "name", "age", "adress", "salary", "join_date")) } return JsonResponse(data) |
Above is the result we get that displays a Json string of the form:
1 2 3 4 5 6 7 8 9 10 11 | { "result" : [ { "id": value, "name": value, "age": value, "adress" : value, "salary" : value, "join_date" :value } ]} |
Specific results we see below.
2.Settings
The next important part we install the DjangoRest framework in the settings.py file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'todos' ] REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ] } |
3.Urls
To get the data we create a string of URLs in the urls.py file:
1 2 3 4 5 6 7 8 9 10 11 12 13 | from django.contrib import admin from django.urls import path, include from rest_framework import routers from todos.api.viewset import getJson router = router. DefaultRouter() urlpattenrns = [ path('admin/',admin.site.urls), path(r'',include(router.urls), path(r'api/data/', getJson, name='getJson') ] |
We can customize the URL in the path above.
4.Run
So we have completed the API construction code. To run, we use the command:
1 2 3 4 5 6 | python manage.py makemigrations python manage.py migrate # Run python manage.py runserver |
When start we see:
We will run the server above us:
We add / admin to the link above and we will get to the admin page. Note : It is important that you create createsuperuser before you go to this page. How to create it in the above Viblo link. Upon entering we will see the Company table and when clicked we will see the fields we have code in models.py : Figure 1. The first link
We try adding the data to SAVE:
So we have the data. Now take the Json data. Recall that when we code urls.py the URL had /api/data added.
Try Postman:
Delicious peach branches.Hehe !!
We also check to see if the db has been created using the terminal:
OK …
Conclude
So we created a simple app using the Django Rest framework using PostgresSQL. During the implementation, we will encounter some errors about PostgresSQL connection with Django, unable to insert data, unable to get data, … if you feel stress, please stand up and go back, drink water and then fix the error again though not know if you will succeed In addition, you also access the link: https://www.django-rest-framework.org/tutorial/quickstart/ to see more interesting things. Good luck. See you on the next article.