What is the REST API?
什么是REST API?
To know what is REST API, let’s first understand what is an API. An API is a set of code that allows much software to communicate with each other. It is abbreviated as Application Program Interface. Then what is REST API? REST API is an architectural style that defines a set of rules to be used while creating web services. If an API follows these rules, then the API is a REST API. REST API is abbreviated as REpresentational State Transfer.
要了解什么是REST API,首先让我们了解什么是API。 API是一组代码,允许许多软件相互通信。 它简称为A pplication 页程序我覆盖整个院落。 那么什么是REST API? REST API是一种体系结构样式,它定义了在创建Web服务时要使用的一组规则。 如果API遵循这些规则,则该API是REST API。 REST API缩写为RE表象小号泰特贸易交接。
The four main API requests are GET, POST, PUT, DELETE.
四个主要的API请求是GET,POST,PUT,DELETE。
GET —This request is made when we wanna request some data from the server. Eg: Fetching weather forecast from the weather API.
GET-当我们想从服务器请求一些数据时,发出此请求。 例如:从天气API获取天气预报。
POST — This request is made when we wanna add data to the server. Eg: User Registration and Login.
POST —当我们想向服务器添加数据时发出此请求。 例如:用户注册和登录。
PUT — This request is for changing any Existing information in the server. Eg: Updating User Profile.
PUT —此请求用于更改服务器中的任何现有信息。 例如:更新用户个人资料。
DELETE — As the name indicates, this request is made where we wanna delete any existing information.
DELETE —顾名思义,此请求是在我们要删除任何现有信息的地方发出的。
In this blog, I just explaining how to create a simple REST API with Django’s Django Rest Framework.
在此博客中,我仅说明了如何使用Django的Django Rest Framework创建简单的REST API。
Create a Django Project
创建一个Django项目
So now let’s start creating our Django project. I am creating a Django project named drf
. After creating, just migrate the project.
现在开始创建Django项目。 我正在创建一个名为drf
的Django项目。 创建后,只需迁移项目。
$ django-admin startproject drf
$ cd drf
$ python3 manage.py migrate
$ python3 manage.py runserver
2. Install Django Rest Framework
2. 安装Django Rest Framework
Django Rest Framework is one of the toolkits built for developing web APIs.
Django Rest Framework是为开发Web API而构建的工具箱之一。
So now let’s install Django Rest Framework.
现在,让我们安装Django Rest Framework。
$ pip3 install djangorestframework markdown django-filter
This command will install the Django rest framework into our project.
此命令会将Django rest框架安装到我们的项目中。
Now add our restframework
to the installed apps.
现在,将restframework
添加到已安装的应用程序中。
drf/settings.py
drf/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles', 'rest_framework', # make Sure to add this line
]
3. Creating a Model
3. 创建模型
Create a new App student
in the drf
project where we’ll be creating our model.
在drf
项目中创建一个新的App student
,我们将在其中创建模型。
$ python3 manage.py startapp student
This command will create a new app named student
. Now let’s start creating our model. Don't forget to add the app to our installed apps.
此命令将创建一个名为student
的新应用。 现在开始创建模型。 不要忘记将应用程序添加到我们已安装的应用程序中。
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework','student', # make Sure to add this line
]
Now I am just including my new App’s urls.py
in the project level urls.py
file.
现在,我将新应用程序的urls.py
在项目级别的urls.py
文件中。
drf/urls.py
drf/urls.py
from django.conf.urls import url
from django.urls import path, include
from django.contrib import adminurlpatterns = [
url(r'^admin/', admin.site.urls), path('student/', include('student.urls'))]
Now let’s start creating our model.
现在开始创建模型。
student/models.py
student/models.py
from django.db import models# Create your models here.
class Student(models.Model):
student_reg_number = models.TextField(unique=True)
student_name = models.TextField()
student_email = models.TextField()
student_mobile = models.TextField(null=True)
created_at = models.DateTimeField(auto_now=True)
After creating the model file just migrate.
创建模型文件后,只需迁移即可。
$ python3 manage.py makemigrations
$ python3 manage.py migrate
The command will initially create a new migration file and then migrate our changes to the database.
该命令将首先创建一个新的迁移文件,然后将我们的更改迁移到数据库。
4. Creating API and Serializer Class:
4. 创建API和序列化器类:
Now everything is good. We have created our model successfully. Now let’s get into the API section.
现在一切都很好。 我们已经成功创建了模型。 现在让我们进入“ API”部分。
To create an API we need two files, serializer
file, and theapi or view
file. Basically, the serializer
is something that converts the instance given to the API into python or the native language’s datatype that can be converted into json
or xml
format. A api
is the initial point of contact from the URL. We can also use the default view.py
file. But I am not using it to create API. Each and every programmer have their own way of coding. I prefer to keep api
as a separate file.
要创建API,我们需要两个文件,即serializer
程序文件和api or view
文件。 基本上, serializer
程序可以将提供给API的实例转换为python或可以转换为json
或xml
格式的本地语言的数据类型。 api
是URL的初始联系点。 我们还可以使用默认的view.py
文件。 但是我没有用它来创建API。 每个程序员都有自己的编码方式。 我更喜欢将api
保留为单独的文件。
So now let’s create api.py
and serializer.py
files in the student
app. So the app structure must be student/api.py
and student/serializer.py
.
现在,让我们在student
应用程序中创建api.py
和serializer.py
文件。 因此,应用程序结构必须为student/api.py
和student/serializer.py
。
student/serializer.py
student/serializer.py
from rest_framework import serializers
from .models import Studentclass StudentSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = '__all__'
student/api.py
student/api.py
from rest_framework import generics
from rest_framework.response import Response
from .serializer import StudentSerializer
from .models import Studentclass StudentApi(generics.ListCreateAPIView):
queryset = Student.objects.all()
serializer_class = StudentSerializer
Here the ListCreateAPIView
is the class that helps us to create both POST and GET requests.
这里的ListCreateAPIView
是可帮助我们创建POST和GET请求的类。
Now map our StudentApi
with a URL as shown.
现在,使用如图所示的URL映射我们的StudentApi
。
student/urls.py
student/urls.py
from django.urls import path
from .api import StudentApiurlpatterns = [
path('api',StudentApi.as_view()),
]
Now your code is ready. Just run your server. Navigate to the browser and open http://localhost:8000/student/api. You should see a screen as shown. If you have used node before, you would have used something called Swagger
. It is an online UI client to make Http requests. Similarly, DRF provides the same, as an inbuilt functionality where you can make all the PUT, GET, POST, and DELETE requests.
现在您的代码已准备就绪。 只需运行您的服务器。 导航到浏览器,然后打开http:// localhost:8000 / student / api 。 您应该看到如下所示的屏幕。 如果您以前使用过node,那么您将使用Swagger
。 它是发出Http请求的在线UI客户端。 同样,DRF提供了与内置功能相同的功能,在其中您可以发出所有PUT,GET,POST和DELETE请求。
![Image for post](https://miro.medium.com/max/9999/1*lYpnp9NrA3bFvN98hfeaAw.png)
Also, you can check if it works with Postman. The below image is a demonstration for the POST request.
另外,您可以检查它是否适用于Postman。 下图是POST请求的演示。
![Image for post](https://miro.medium.com/max/9999/1*7xpn6HCTSpY2jq8u1d4_yA.png)
This image is a demonstration for GET request.
此图像是GET请求的演示。
![Image for post](https://miro.medium.com/max/9999/1*xvn8EPOzC946Xu8-N2BN2Q.png)
Another cool feature I personally like in DRF is that it handles errors. In my model, I have created student_reg_number
to be unique and required. So if the request from the client didn’t send the required field, it sends error response. Cool right. I found it difficult with node js. But now the node has some packages to handle it.
我个人在DRF中喜欢的另一个很酷的功能是它可以处理错误。 在我的模型中,我创建了student_reg_number
,它是唯一且必需的。 因此,如果来自客户端的请求未发送必填字段,则会发送错误响应。 酷吧。 我发现使用节点js很难。 但是现在该节点有一些软件包可以处理它。
![Image for post](https://miro.medium.com/max/9999/1*k3BtXB6tvU00aMsDEAurMw.png)
![Image for post](https://miro.medium.com/max/9999/1*Jc_kokL2rFaLC-KzeNuGqQ.png)
In my next blog, I will be performing CRUD functionality with Django Rest Framework. Stay Connected.
在下一个博客中,我将使用Django Rest Framework执行CRUD功能。 保持联系。
Feel free to contact me for any queries.
如有任何疑问,请随时与我联系。
Email: sjlouji10@gmail.com
电子邮件:sjlouji10@gmail.com
Linkedin: https://www.linkedin.com/in/sjlouji/
Linkedin: https : //www.linkedin.com/in/sjlouji/
Complete Code can be found on my Github: https://github.com/sjlouji/Django---DRF-basic-Rest-API-.git
完整的代码可以在我的Github上找到: https : //github.com/sjlouji/Django---DRF-basic-Rest-API-.git
Happy coding…
编码愉快!
翻译自: https://medium.com/swlh/django-rest-framework-creating-a-simple-api-in-15mins-with-drf-5e051ee531dd