django rest framework用drf在15分钟内创建一个简单的api

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。

  1. 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或可以转换为jsonxml格式的本地语言的数据类型。 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.pyserializer.py文件。 因此,应用程序结构必须为student/api.pystudent/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
Django Rest Framework’s inbuild UI like Swagger
Django Rest Framework的内置UI(例如Swagger)

Also, you can check if it works with Postman. The below image is a demonstration for the POST request.

另外,您可以检查它是否适用于Postman。 下图是POST请求的演示。

Image for post
DRF POST request
DRF POST请求

This image is a demonstration for GET request.

此图像是GET请求的演示。

Image for post
DRF get request
DRF收到请求

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
Image for post
Error Handling Page — Postman
错误处理页面-邮递员

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
本季课程把开发知识拆解到项目里,让你在项目情境里学知识。这样的学习方式能让你保持兴趣、充满动力,时刻知道学的东西能用在哪、能怎么用。平时不明白的知识点,放在项目里去理解就恍然大悟了。  一、融汇贯通本视频采用了前后端分离的开发模式,前端使用Vue.js+Element UI实现了Web页面的呈现,后端使用PythonDjango REST Framework框架实现了数据访问的接口,前端通过Axios访问后端接口获得数据。在学习完本章节后,真正理解前后端的各自承担的工作。 二、贴近实战本课程为学生信息管理系统课程:Vue3 + Vite + ElementPlus + Django REST Framework项目实战 本季课程主学生信息管理系统V5.0,内容包含:Django REST framework安装和项目初始化、数据的序列化、ViewSet视图集、DefaultRouter路由类、django-filter实现过滤、rest framework实现查找、rest framework实现分页、npm的使用、使用Vite构建vue3项目、Package.json解析、ElementPlus安装和应用、vue-router实现路由、使用Vuex的store对象、后台管理系统主界面的布局、axios组件的安装和请求、axios请求的模块化、请求拦截器和响应拦截器、使用el-select实现联级下拉、使用cascader实现联级选择、vue表单的验证、实现学生信息的添加、修改和删除、实现文件的上传等等功能 本案例完整的演示了项目实现过程,虽然不复杂,但涉及的内容非常多,特别是前后端交互的时候,有诸多的坑等着你去踩,好在王老师全程代码呈现,带着大家一起填坑,大大提高学习效率的同时,也培养了大家良好的代码习惯,希望大家一起跟着王进老师学习Python开发。三、后续课程预告:Vue和Django REST Framework实现JWT登录认证 

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值