[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.

 

posted @   Zhentiw  阅读(172)  评论(0编辑  收藏  举报
编辑推荐:
· 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?
点击右上角即可分享
微信分享提示