Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

django rest framework

### 1- install libraries ###
pip install djangorestframework
pip install markdown       # Markdown support for the browsable API.
pip install django-filter  # Filtering support

### 2- add rest framework to installed apps in settings.py ###
INSTALLED_APPS = [
    ...
    'rest_framework',
]

### 3- create serializers.py file (used to process python objects into json format) ###
from rest_framework import serializers
from .models import Drink

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = ['id', 'name', 'description']
        
### 4- in views.py create the view that handle the whole process ###
from django.http import JsonResponse
from .models import Product
from .serializers import ProductSerializer

def getProductsAsJson(request):
    products = Product.objects.all()
    serializer = ProductSerializer(product, many=True)
    return JsonResponse(serializer.data, safe=False)
  
### 5- you can now add this view in urls.py and try it ###
Source by www.django-rest-framework.org #
 
PREVIOUS NEXT
Tagged: #django #rest #framework
ADD COMMENT
Topic
Name
6+3 =