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<code>\w+)/$', views.course_details), path('rest_client/', views.client), ]
python manage.py runserver
<html> <head> <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script> <script> var URL = "/rest_courses/"; $(document).ready( function() { $("#courses").hide(); } ); function getCourses() { $.getJSON(URL,{},showCourses); } function getCourse() { $.getJSON(URL + $("#code").val()) .done(showCourse) // on success - 200 .fail(function() // on failure - 404 { alert("Sorry! Course Not Found!"); } ); } function showCourse(course) { $("#title").val(course.title) $("#duration").val(course.duration) $("#fee").val(course.fee) } function showCourses(courses) { $("#courserows").html("") $.each(courses, function(idx,course) { $("#courserows").append("<tr><td>" + course.code + "</td><td>" + course.title + "</td><td>" + course.duration + "</td><td>" + course.fee + "</td></tr>"); } // anonymous function ); // each() $("#courses").show(); } // showCourses function addCourse() { $.ajax( { "url": URL, "data": { "code" : $("#code").val(), "title" : $("#title").val(), "duration" : $("#duration").val(), "fee" : $("#fee").val() }, "type" : "post", "success" : add_success, "error" : add_error } ); // ajax() } function add_success() { alert("Added course Successfully"); } function add_error() { alert("Could not add course!"); } function deleteCourse() { $.ajax( { "url": URL + $("#code").val(), "type" : "delete", "success" : delete_success, "error" : delete_error } ); // ajax() } function delete_success() { alert("Deleted Course Successfully"); } function delete_error() { alert("Could not delete Course!"); } function updateCourse() { $.ajax( { "url" : URL + $("#code").val() + "/", "data" : { "code" : $("#code").val(), "title" : $("#title").val(), "duration" : $("#duration").val(), "fee" : $("#fee").val() }, "type" : "put", "success" : update_success, "error" : update_error } ); // ajax() } function update_success() { alert("Updated Course Successfully"); } function update_error() { alert("Could not update Course!"); } </script> </head> <body> <div style="background-color:navy;color:white;font-family:arial;font-size:20pt;font-weight:bold">Course Client</div> <p/> Code <br/> <input type="text" id="code"/> <br/> Title <br/> <input type="text" id="title"/> <br/> Duration <br/> <input type="number" id="duration"/> <br/> Fee <br/> <input type="number" id="fee"/> <p/> <button onclick="getCourse()">Details</button> <button onclick="addCourse()">Add </button> <button onclick="deleteCourse()">Delete </button> <button onclick="updateCourse()">Update </button> <button onclick="getCourses()">List</button> <p/> <table border="1" cellpadding="5pt" id="courses"> <thead> <tr> <th>Code</th> <th>Title</th> <th>Duration</th> <th>Fee</th> </tr> </thead> <tbody id="courserows"></tbody> </table> </body> </html>