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!

There are many methods to connect two lists in Python: 1. Use operators, which are simple but inefficient in large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use the = operator, which is both efficient and readable; 4. Use itertools.chain function, which is memory efficient but requires additional import; 5. Use list parsing, which is elegant but may be too complex. The selection method should be based on the code context and requirements.

There are many ways to merge Python lists: 1. Use operators, which are simple but not memory efficient for large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use itertools.chain, which is suitable for large data sets; 4. Use * operator, merge small to medium-sized lists in one line of code; 5. Use numpy.concatenate, which is suitable for large data sets and scenarios with high performance requirements; 6. Use append method, which is suitable for small lists but is inefficient. When selecting a method, you need to consider the list size and application scenarios.

Compiledlanguagesofferspeedandsecurity,whileinterpretedlanguagesprovideeaseofuseandportability.1)CompiledlanguageslikeC arefasterandsecurebuthavelongerdevelopmentcyclesandplatformdependency.2)InterpretedlanguageslikePythonareeasiertouseandmoreportab

In Python, a for loop is used to traverse iterable objects, and a while loop is used to perform operations repeatedly when the condition is satisfied. 1) For loop example: traverse the list and print the elements. 2) While loop example: guess the number game until you guess it right. Mastering cycle principles and optimization techniques can improve code efficiency and reliability.

To concatenate a list into a string, using the join() method in Python is the best choice. 1) Use the join() method to concatenate the list elements into a string, such as ''.join(my_list). 2) For a list containing numbers, convert map(str, numbers) into a string before concatenating. 3) You can use generator expressions for complex formatting, such as ','.join(f'({fruit})'forfruitinfruits). 4) When processing mixed data types, use map(str, mixed_list) to ensure that all elements can be converted into strings. 5) For large lists, use ''.join(large_li

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

ThekeydifferencesbetweenPython's"for"and"while"loopsare:1)"For"loopsareidealforiteratingoversequencesorknowniterations,while2)"while"loopsarebetterforcontinuinguntilaconditionismetwithoutpredefinediterations.Un

In Python, you can connect lists and manage duplicate elements through a variety of methods: 1) Use operators or extend() to retain all duplicate elements; 2) Convert to sets and then return to lists to remove all duplicate elements, but the original order will be lost; 3) Use loops or list comprehensions to combine sets to remove duplicate elements and maintain the original order.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
