该文章收录专栏
Rest API,开放数据接口
我们按照官方文档一步一步安装
- 安装对应依赖
- 添加
app
到settings
- 添加路由
path('api-auth/', include('rest_framework.urls'))
- 创建自己的API序列类和视图
""" API """ from django.contrib.auth.models import User from rest_framework import routers, serializers, viewsets from jobs.models import Jobs # Serializers define the API representation. class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['url', 'username', 'email', 'is_staff'] class JobSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Jobs fields = '__all__' # 全部 # ViewSets define the view behavior. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer # ViewSets define the view behavior. class JobViewSet(viewsets.ModelViewSet): queryset = Jobs.objects.all() serializer_class = JobSerializer
- 添加路由
# Routers provide an easy way of automatically determining the URL conf. router = routers.DefaultRouter() router.register(r'users', UserViewSet) router.register(r'jobs', JobViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] urlpatterns = ( # django rest api & api auth (login/logout) path('api/', include(router.urls)), path('api-auth/', include('rest_framework.urls')) )
- 运行服务器🎉🎉🎉
🤞到这里,如果还有什么疑问🤞 🎩欢迎私信博主问题哦,博主会尽自己能力为你解答疑惑的!🎩 🥳如果对你有帮助,你的赞是对博主最大的支持!!🥳