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

原文地址:https://www.cnblogs.com/Answer1215/p/6517642.html