1、什么是RESTful html
2、什么是API前端
3、RESTful API规范vue
4、基于Django实现APIgit
5、基于Django Rest Framework框架实现github
一、什么是API?ajax
答:API就是接口,提供的url。接口有两个用途:数据库
网络应用程序,分为前端和后端两个部分。当前的发展趋势,就是前端设备层出不穷(手机、平板、桌面电脑、其余专用设备......)。django
所以,必须有一种统一的机制,方便不一样的前端设备与后端进行通讯。这致使API构架的流行,甚至出现"API First"的设计思想。RESTful API是目前比较成熟的一套互联网应用程序的API设计理论。json
API与用户的通讯协议,老是使用HTTPs协议。后端
1.不用大写; 2.用中杠 - 不用下杠 _ ; 3.参数列表要encode; 4.URI中的名词表示资源集合,使用复数形式。 5.在RESTful架构中,每一个网址表明一种资源(resource),因此网址中不能有动词,只能有名词(特殊状况可使用动词),并且所用的名词每每与数据库的表格名对应。
# 方式一: 尽可能将API部署在专用域名(会存在跨域问题) https://api.example.com # 方式二:若是肯定API很简单,不会有进一步扩展,能够考虑放在主域名下。 https://example.org/api/
应该将API的版本号放入URL。
https://api.example.com/v1/
https://api.example.com/v1/zoos
https://api.example.com/v1/zoos/1/animals
另外一种作法是,将版本号放在HTTP头信息中,但不如放入URL方便和直观。Github采用这种作法。
URI表示资源的两种方式:资源集合、单个资源。 资源集合: /zoos # 全部动物园 /zoos/1/animals # id为1的动物园中的全部动物 单个资源: /zoos/1 # id为1的动物园 /zoos/1;2;3 # id为1,2,3的动物园 结合版本 https://api.example.com/v1/zoos https://api.example.com/v1/animals https://api.example.com/v1/employees
在url中表达层级,用于 按实体关联关系进行对象导航 ,通常根据id导航。
过深的导航容易致使url膨胀,不易维护,如 GET /zoos/1/areas/3/animals/4 ,尽可能使用查询参数代替路径中的实体导航,如 GET/animals?zoo=1&area=3 ;
# 经常使用的HTTP动词有下面五个(括号里是对应的SQL命令) GET(SELECT):从服务器取出资源(一项或多项)。即获取数据 POST(CREATE):在服务器新建一个资源。 即添加数据 PUT(UPDATE):在服务器更新资源(客户端提供改变后的完整资源,即完整的数据)。即更新数据。与下面的PATCH相似。 PATCH(UPDATE):在服务器更新资源(客户端提供改变的属性,即一部分数据)。即更新数据。 DELETE(DELETE):从服务器删除资源 。即删除数据 # 用的很少的 HEAD / OPTION HEAD:获取资源的元数据 OPTIONS:获取信息,关于资源的哪些属性是客户端能够改变的
GET /zoos # 列出全部动物园 GET /zoos/ID # 获取某个指定动物园的信息 GET /zoos/ID/animals # 列出某个指定动物园的全部animals POST /zoos # 新建一个动物园 POST /zoos/1/employees # 为id为1的动物园雇佣员工 PUT /zoos/ID # 更新某个指定动物园的信息(提供该动物园的所有信息) PATCH /zoos/ID # 更新某个指定动物园的信息(提供该动物园的部分信息) DELETE /zoos/ID # 删除某个动物园 DELETE /zoos/ID/animals/ID # 删除某个指定动物园的指定动物 DELETE /zoos/ID/animals/2;5;6;8 # 删除某个指定动物园的指定动物,使用";"表示多个
若是记录数量不少,服务器不可能都将它们返回给用户。API应该提供参数,过滤返回结果。
下面是一些常见的参数。
# 分页相关 ?limit=10 # 指定返回记录的数量 ?offset=10 # 指定返回记录的开始位置。 ?page=2&per_page=100 # 指定第几页,以及每页的记录数。 # 排序相关 ?sortby=name&order=asc # 指定返回结果按照哪一个属性排序,以及排序顺序。 # 过滤条件 ?type=1&age=16 # 容许必定的uri冗余,如 /zoos/1 与 /zoos?id=1 ?animal_type_id=1 # 指定筛选条件 # 投影 ?whitelist=id,name,email
参数的设计容许存在冗余,即容许API路径和URL参数偶尔有重复。好比,GET /zoo/ID/animals 与 GET /animals?zoo_id=ID 的含义是相同的。
· |
response 格式 |
GET |
单个对象、集合 |
POST |
新增成功的对象 |
PUT/PATCH |
更新成功的对象 |
DELETE |
空 |
# 服务器向用户返回的状态码和提示信息,常见的有如下一些(方括号中是该状态码对应的HTTP动词)。 200 OK - [GET]:服务器成功返回用户请求的数据,该操做是幂等的(Idempotent)。 201 CREATED - [POST/PUT/PATCH]:用户新建或修改数据成功。 202 Accepted - [*]:表示一个请求已经进入后台排队(异步任务) 204 NO CONTENT - [DELETE]:用户删除数据成功。 400 INVALID REQUEST - [POST/PUT/PATCH]:用户发出的请求有错误,服务器没有进行新建或修改数据的操做,该操做是幂等的。 401 Unauthorized - [*]:表示用户没有权限(令牌、用户名、密码错误)。 403 Forbidden - [*] 表示用户获得受权(与401错误相对),可是访问是被禁止的。 404 NOT FOUND - [*]:用户发出的请求针对的是不存在的记录,服务器没有进行操做,该操做是幂等的。 406 Not Acceptable - [GET]:用户请求的格式不可得(好比用户请求JSON格式,可是只有XML格式)。 410 Gone -[GET]:用户请求的资源被永久删除,且不会再获得的。 422 Unprocesable entity - [POST/PUT/PATCH] 当建立一个对象时,发生一个验证错误。 500 INTERNAL SERVER ERROR - [*]:服务器发生错误,用户将没法判断发出的请求是否成功。 # URI失效 随着系统发展,总有一些API失效或者迁移,对失效的API,返回404 not found 或 410 gone;对迁移的API,返回 301重定向。
状态码的彻底列表参见这里。
常用的、复杂的查询标签化,下降维护成本。
如:GET /trades?status=closed&sort=created,desc
快捷方式:GET /trades#recently-closed或者GET /trades/recently-closed
1. 不要发生了错误却给2xx响应,客户端可能会缓存成功的http请求;
2. 正确设置http状态码,不要自定义;
3. Response body提供
即:返回的信息中将error做为键名,出错信息做为键值便可
1)错误的代码(日志/问题追查);
2)错误的描述文本(展现给用户)。
若是状态码是4xx,就应该向用户返回出错信息。通常来讲,返回的信息中将error做为键名,出错信息做为键值便可。
{ code: 10086, error: "Invalid API key" }
RESTful API最好作到Hypermedia,即返回结果中提供连接,连向其余API方法,使得用户不查文档,也知道下一步应该作什么。
好比,当用户向api.example.com的根目录发出请求,会获得这样一个文档。
{"link": { "rel": "collection https://www.example.com/zoos", #表示这个API与当前网址的关系(collection关系,并给出该collection的网址) "href": "https://api.example.com/zoos", #API路径 "title": "List of zoos", #API的标题 "type": "application/vnd.yourformat+json" #返回类型 }}
Hypermedia API的设计被称为HATEOAS。Github的API就是这种设计,访问api.github.com会获得一个全部可用API的网址列表。
{ "current_user_url": "https://api.github.com/user", "authorizations_url": "https://api.github.com/authorizations", // ... }
从上面能够看到,若是想获取当前用户的信息,应该去访问api.github.com/user,而后就获得了下面结果。
{ "message": "Requires authentication", "documentation_url": "https://developer.github.com/v3" }
from django.contrib import admin from django.conf.urls import url, include from app01 import views from app02 import views urlpatterns = [ url('admin/', admin.site.urls), # path('hosts/',views.HostView.as_view()), url('app02/', include('app02.urls')) ]
from app02 import views from django.conf.urls import url urlpatterns = [ url('^users/', views.users), url('^user/(\d+)', views.user), url('^users/', views.UsersView.as_view()), url('^user/', views.UserView.as_view()), ]
from django.shortcuts import render,HttpResponse # Create your views here. import json def users(request): response = {'code':1000,'data':None} #code用来表示状态,好比1000表明成功,1001表明 response['data'] = [ {'name':'haiyan','age':22}, {'name':'haidong','age':10}, {'name':'haixiyu','age':11}, ] return HttpResponse(json.dumps(response)) #返回多条数据 def user(request,pk): if request.method =='GET': return HttpResponse(json.dumps({'name':'haiyan','age':11})) #返回一条数据 elif request.method =='POST': return HttpResponse(json.dumps({'code':1111})) #返回一条数据 elif request.method =='PUT': pass elif request.method =='DELETE': pass
from app02 import views from django.conf.urls import url urlpatterns = [ url('^users/', views.UsersView.as_view()), url('^user/', views.UserView.as_view()), ]
from django.views import View class UsersView(View): def get(self,request): response = {'code':1000,'data':None} response['data'] = [ {'name': 'haiyan', 'age': 22}, {'name': 'haidong', 'age': 10}, {'name': 'haixiyu', 'age': 11}, ] return HttpResponse(json.dumps(response),stutas=200) class UserView(View): def get(self,request,pk): return HttpResponse(json.dumps({'name':'haiyan','age':11})) #返回一条数据 def post(self,request,pk): return HttpResponse(json.dumps({'code':1111})) #返回一条数据 def put(self,request,pk): pass def delete(self,request,pk): pass
基于django实现的API许多功能都须要咱们本身开发,这时候djangorestframework就给咱们提供了方便,直接基于它来返回数据,总之原理都是同样的,就是给一个接口也就是url,让前端的人去请求这个url去获取数据,在页面上显示出来。这样也就达到了先后端分离的效果。下面咱们来看看基于Django Rest Framework框架实现
详见连接
class MyAuthtication(BasicAuthentication): def authenticate(self, request): token = request.query_params.get('token') #注意是没有GET的,用query_params表示 if token == 'zxxzzxzc': return ('uuuuuu','afsdsgdf') #返回user,auth raise APIException('认证错误') class UserView(APIView): authentication_classes = [MyAuthtication,] def get(self,request,*args,**kwargs): print(request.user) print(request.auth) return Response('用户列表')
主要是作Token验证 url中as_view里面调用了dispatch方法。
能够有两种方式
from app01 import views from django.conf.urls import url urlpatterns = [ # django rest framework url('^hosts/', views.HostView.as_view()), url(r'^auth/', views.AuthView.as_view()), ]
from django.shortcuts import render,HttpResponse # Create your views here. from rest_framework.views import APIView from rest_framework.views import Request from rest_framework.authentication import SessionAuthentication from rest_framework.authentication import BaseAuthentication, BasicAuthentication from rest_framework.parsers import JSONParser from rest_framework.negotiation import DefaultContentNegotiation from rest_framework.exceptions import APIException from app01 import models from rest_framework.response import Response #友好的显示返回结果 class AuthView(APIView): #auth登陆页面不须要验证,可设置 authentication_classes = [] #登陆页面不须要认证 def get(self,request): ''' 接收用户名和密码 :param request: :return: ''' ret = {'code':1000,'msg':None} user = request.query_params.get('username') pwd = request.query_params.get('password') print(user,pwd) obj = models.UserInfo.objects.filter(username=user,password=pwd).first() print(obj) if not obj : ret['code'] = 1001 ret['msg'] = '用户名或者密码错误' return Response(ret) #建立随机字符串 import time import hashlib ctime = time.time() key = '%s|%s'%(user,ctime) m = hashlib.md5() m.update(key.encode('utf-8')) token = m.hexdigest() #保存数据 obj.token = token obj.save() ret['token'] = token return Response(ret) class HostView(APIView): def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) # authentication_classes = [MyAuthtication] def get(self,request,*args,**kwargs): print(request.user,'dddddddddddffffff') print(request.auth,'dddddddddd') #原来的request,django.core.handlers.wsgi.WSGIRequest #如今的request ,rest_framework.request.Request # print(request) authentication_classes = [SessionAuthentication,BaseAuthentication] # print(self.authentication_classes) # [<class 'rest_framework.authentication.SessionAuthentication'>, # <class 'rest_framework.authentication.BasicAuthentication'>] return HttpResponse('GET请求的响应内容') def post(self,request,*args,**kwargs): pass # try: # try : # current_page = request.POST.get("page") # # current_page = int(current_page) # int("asd") # except ValueError as e: # print(e) # raise #若是有raise说明本身处理不了了,就交给下面的一个去捕捉了 # except Exception as e: # print("OK") return HttpResponse('post请求的响应内容') def put(self, request, *args, **kwargs): return HttpResponse('put请求的响应内容')
#注册认证类 REST_FRAMEWORK = { 'UNAUTHENTICATED_USER': None, 'UNAUTHENTICATED_TOKEN': None, #将匿名用户设置为None "DEFAULT_AUTHENTICATION_CLASSES": [ "app01.utils.MyAuthentication", ], }
from rest_framework.authentication import BaseAuthentication from rest_framework.exceptions import APIException from app02 import models class MyAuthentication(BaseAuthentication): def authenticate(self, request): token=request.query_params.get('token') print(token) obj=models.UserInfo.objects.filter(token=token).first() print(obj) if obj: return (obj.username,obj) raise APIException('没有经过验证')
注:rest_framewor是一个app须要settings里面设置。