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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

How Much Python Can You Learn in 2 Hours? How Much Python Can You Learn in 2 Hours? Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

See all articles