In this article, I will explain Rest Framework. Before going into technical details, let's talk a little bit about what Rest Framework is.
Rest Framework is an advanced framework that allows us to code a common back-end for both mobile applications, web applications and desktop applications. For example, you can use a back-end server that you coded with Rest Framewok in both your mobile application and your web application.
You can develop your applications by using Rest Framework with front end technologies such as Angular, React, Vue. Since Rest Framework gives responses in a common structure in programming, you can use these outputs with either Angular or React. So what are the types of these outputs? Of course, structures like JSON. Optionally, you can send these outputs in different structures to the front-end side, of course. Now let's move on to Coding
Creating a Project
1) django-admin startproject projeName
We have created our project. Now let's run our project.
2) python manage.py runserver
Then, let's write the necessary commands to create the necessary tables in our database.
3) python manage.py migrate
Let's not forget to add the application we created to the INSTALLED_APPS directory under the settings.py file.
Everything is ok. Now we can move on to the necessary steps for the rest framework.
To install Rest Framework on our computer, we need to run the following commands in our terminal.
1) pip install djangorestframework
for example;
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'POSTAPP',
]
Now that we have added the Rest framework, we can start creating the API. To do this, we need to create a folder called API and some files in the application folder we created. Let's add these files:
YOUR_PROJECT/
api/
init.py
views.py
urls.py
serializers.py
With the ** init.py** file, we indicate that this folder is a Python module
The views.py ** file is the file where we will write the classes or functions that will provide the answers we will send to incoming requests.
The **urls.py file is the file where we will set our API urls, as you can guess from the structure of Django.
The serializers.py file is the file in which we will write the structures that will put our incoming query sets into the formats we want (JSON, for example). We will get into the details of this gradually.
First, let's go to the urls.py file that comes ready in the main folder of our project and define the url paths according to the API folder we created.
urlpatterns = [
path('admin/', admin.site.urls),
path("api/post/",include("YOUR_PROJECT.api.urls",namespace="post")),
]
We already have an admin path. We also added a new path as api/post. With the Include method, we redirected the requests coming to api/post/ to our url file in the API folder we created.
Now, let's quickly write a model for the post we created. Let's come to the models.py file in the YOUR_PROJECT folder.
class PostModel(models.Model):
Author = models.ForeignKey(User,on_delete=models.CASCADE)
Title = models.CharField(max_length=50)
Content = models.TextField()
Draft = models.BooleanField(default=False)
ModifiedDate = models.DateTimeField(editable=False)
After creating our model, let's write the necessary codes in our terminal to create tables in the database.
python manage.py makemigrations
With these codes, we created the Python files necessary to create tables in our database. We will run the following commands to create the tables.
*python manage.py migrate *
Now let's come to our empty urls.py file in the api folder under the YOUR_PROJECT directory we created.
from django.urls import path
from .views import YourProjectAPIView
app_name="post"
urlpatterns = [
path("list/",YourProjectAPIView.as_view(),name="your_project"),
]
First, we specified an application name with app_name=”post”.
Now, we tried to import the views that we have not created yet and tried to use them according to our path. Let's immediately create the views whose names we wrote in our views.py file under the YOUR_PROJECT/api directory.
First, let's create a view in which we will send all the posts in the database with the request in a JSON structure.
from POSTAPP.models import PostModel
from rest_framework.generics import ListAPIView
class PostListAPIView(ListAPIView):
serializer_class = PostSerializer
queryset = PostModel.objects.all()
Let's explain what we did here. We created a view using the ListAPIView class, which comes ready for the listing process in the Rest Framework. First, we determine which model we will return with the queryset variable. And we need to specify our serializer class that will serialize the data coming from this model, that is, the query set. After all, we will not send a queryset to the other party. We will send the serialized JSON object. The structure that will convert the query set into a JSON object will be the serializers we will have created.
For now, I have created a serializer called PostSerializer in the serializer_class variable. We will create this serializer in the serializers.py file in the same directory. Let's create it now.
from rest_framework import serializers
class YourProjectSerializer(serializers.ModelSerializer):
class Meta:
model = PostModel
fields = ["Author","Title","Content",'Draft','ModifiedDate']
Top comments (0)