[Django] Building the rest API
Install the rest api framework:
pip install djangorestfamework
In settings.py:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'scrurumboard', ]
Create serializers to transform python to JSON:
## scrumboard/serializers.py from rest_framework import serializers from .models import List, Card ## Translate python to JSON class ListSerializer(serializers.ModelSerializer): class Meta: model = List fields = '__all__' class CardSerializer(serializers.ModelSerializer): class Meta: model = Card fields = '__all__'
It will according to 'Card' and 'List' Models to generate JSON.
REST API Views:
We also needs to use Views (controllers) to get data from database thought Model and transform to JSON and return to the client.
## scrumboard/api.py from rest_framework.generics import ListAPIView from .serializers import ListSerializer, CardSerializer from .models import List, Card class ListApi(ListAPIView): queryset = List.objects.all() ## get all the List data from databse serializer_class = ListSerializer ## conver to JSON class CardApi(ListAPIView): queryset = Card.objects.all() serializer_class = CardSerializer
CONFIG URLS:
## scrumboard/urls.py from django.conf.urls import url from .api import ListApi, CardApi urlpatterns = [ url(r'^lists$', ListApi.as_view()), url(r'^cards$', CardApi.as_view()) ]
This tells that anthing match sub-url like 'lists' or 'cards', we serve those request with ListApi view or CardApi view.
Then in the default urls.py, we need to set up this app entry url:
from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^scrumboard/', include('scrumboard.urls')) ## match the urls.py file in scrumboard folder ]
Because we added 'rest_framework' into INSTALLED_APPS array, we can visit: http://localhost:8000/scrumboard/cards
TO see the REST API interface.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2016-03-08 [RxJS] Reactive Programming - New requests from refresh clicks -- merge()
2016-03-08 [RxJS] Starting a Stream with SwitchMap & switchMapTo
2016-03-08 [RxJS] Reactive Programming - Rendering on the DOM with RxJS
2016-03-08 [RxJS] Reactive Programming - Why choose RxJS?