pip install django
pip install djangorestframework
django-admin startproject courses
python manage.py startapp restapi
INSTALLED_APPS = [ 'restapi', # Our Application 'rest_framework', # Django REST Framework 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ]
from django.db import models class Course(models.Model): code = models.CharField(max_length=5, null=False, primary_key=True) title = models.CharField(max_length=30, null=False, unique=True) duration = models.IntegerField(null=False) fee = models.IntegerField(null=False) def __str__(self): return self.title class Meta: db_table = "Courses"
python manage.py makemigrations
python manage.py migrate
from rest_framework import serializer from rest_framework.decorators import api_view from rest_framework.response import Response from .models import Course from django.shortcuts import render class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = ('code', 'title', 'duration', 'fee') def client(request): return render(request,"rest_client.html") @api_view(['GET','POST']) def list_courses(request): if request.method == "GET": courses = Course.objects.all() serializer = CourseSerializer(courses, many=True) return Response(serializer.data) else: # Post serializer = CourseSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=201) # Successful post return Response(serializer.errors, status=400) #Invalid data @api_view(['GET','DELETE','PUT']) def course_details(request, code): try: course = Course.objects.get(code=code) except: return Response(status=404) if request.method == 'GET': serializer = CourseSerializer(course) return Response(serializer.data) elif request.method == 'PUT': # Update serializer = CourseSerializer(course, data=request.data) if serializer.is_valid(): serializer.save() # Update table in DB return Response(serializer.data) return Response(serializer.errors, status=400) # Bad request elif request.method == 'DELETE': course.delete() return Response(status=204)
from django.contrib import admin from django.urls import path, re_path from restapi import views urlpatterns = [ path('rest_courses/', views.list_courses), re_path('rest_courses/(?P\w+)/$', views.course_details), path('rest_client/', views.client), ]
\w+)/$', views.course_details), path('rest_client/', views.client), ]
python manage.py runserver
Course Client Code Title Duration Fee Details Add Delete Update List