Home Backend Development Python Tutorial What is Django Rest Framework?

What is Django Rest Framework?

Aug 01, 2024 pm 09:14 PM

What is Django Rest Framework?

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']

The above is the detailed content of What is Django Rest Framework?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

See all articles