0% found this document useful (0 votes)
8 views42 pages

Django RESTFramework

The document provides a comprehensive overview of Django REST Framework (DRF), covering its components, installation, and deployment processes. It explains key concepts like APIs, REST, serializers, views, and testing, along with detailed steps for deploying a Django REST API on Render and other platforms. Additionally, it includes debugging techniques and a comparison of deployment options, making it a useful guide for developers looking to build and deploy APIs using DRF.

Uploaded by

vknow360
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views42 pages

Django RESTFramework

The document provides a comprehensive overview of Django REST Framework (DRF), covering its components, installation, and deployment processes. It explains key concepts like APIs, REST, serializers, views, and testing, along with detailed steps for deploying a Django REST API on Render and other platforms. Additionally, it includes debugging techniques and a comparison of deployment options, making it a useful guide for developers looking to build and deploy APIs using DRF.

Uploaded by

vknow360
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

DJANGO REST FRAMEWORK &

DEPLOYMENT

• DRF,
• Serializers,
• API Views,
• Routers,
• Testing,
• Deployment
WHAT IS AN API?

• API allows applications to communicate.


• Common format: JSON.
• Used by web, mobile, and other services.
WHAT IS REST?

• REST = Representational State Transfer.


• Uses HTTP methods such as GET, POST, PUT, DELETE.
INTRODUCTION TO DJANGO REST
FRAMEWORK
• DRF is a toolkit for building Web APIs with Django.
• Provides serialization, authentication, and browsable
APIs.
WHY USE DJANGO REST
FRAMEWORK?
• Rapid Development: DRF follows Django's "batteries-included" philosophy,
offering ready-made features that speed up API development.

• Browsable API: It provides a user-friendly, web-browsable API interface for


developers to interact with and test API endpoints directly in the browser.

• Serialization: DRF simplifies the complex process of converting Python objects (like
Django models) into data formats easily readable by other applications (e.g., JSON or
XML) and vice versa.

• Authentication & Permissions: It includes built-in, ready-to-use authentication and


permission policies to secure your API endpoints.

• Community & Documentation: DRF has extensive documentation and strong


community support, and is trusted by companies like Mozilla and Red Hat.

• Decoupled Architecture: It enables a decoupled architecture, allowing the backend


API to communicate with various front-end frameworks (like React or mobile apps)
without changing the core backend logic.
KEY COMPONENTS

• Serializers
• Views and ViewSets: Views handle HTTP requests and return
responses, similar to traditional Django views but tailored for
APIs. ViewSets abstract this further by combining related logic
(e.g., list, retrieve, create, update, destroy actions) into a single
class.
• Routers: Automatically generate URL patterns for your ViewSets,
minimizing the manual effort of defining URLs for every CRUD
operation.
• Parsers & Renderers: Determine how data is processed and
presented. The default renderers provide both JSON data for
machines and the interactive HTML for the browsable API.
INSTALLING DRF

• Install using: pip install djangorestframework


• Add 'rest_framework' to INSTALLED_APPS.
SERIALIZERS

• Serializers convert Django models to JSON and JSON


back to Django objects.
EXAMPLE SERIALIZER

from rest_framework import serializers


from .models import Book
class BookSerializer([Link]):
class Meta:
model = Book
fields = '__all__'
API VIEWS

• API views handle HTTP requests.


• They return data responses such as JSON.

from rest_framework.decorators import api_view


from rest_framework.response import Response
from .models import Book
from .serializers import BookSerializer

@api_view(['GET’])
def book_list(request):
books = [Link]()
serializer = BookSerializer(books, many=True)
return Response([Link])
CLASS-BASED VIEWS

• Class-based views organize code better.


from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Book
from .serializers import BookSerializer

class BookList(APIView):

def get(self, request):


books = [Link]()
serializer = BookSerializer(books, many=True)
return Response([Link])
VIEWSETS AND ROUTERS

• ViewSets combine multiple views.


from rest_framework import viewsets
from .models import Book
from .serializers import BookSerializer

class BookViewSet([Link]):
queryset = [Link]()
serializer_class = BookSerializer
• Routers automatically generate URL routes.

from rest_framework.routers import DefaultRouter


from .views import BookViewSet

router = DefaultRouter()
[Link](r'books', BookViewSet)

urlpatterns = [Link]
TESTING APIS

• Test APIs using tools like Postman, curl, or DRF


browsable API.
• Testing means checking whether your API works
correctly.
USING POSTMAN

• Create workspace
• Get Httprequest
• Response as json
USING CURL

• how APIs work from the command line without tools like Postman.

• It directly sends HTTP requests to your API built with Django REST
Framework and hosted on Render.

• Get / Retrieve all books

curl [Link]

• Post /create a book detail

Invoke-RestMethod -Uri "[Link] `

-Method POST `

-Headers @{ "Content-Type" = "application/json" } `

-Body '{"title":"REST API Guide","author":"Alice","price":450}'


DEBUGGING

• Finding and fixing errors in your code.


• Common Django errors are :
Error Reason Fix

404 Not Found Wrong URL Check [Link]

500 Error Code crash Check terminal

ModuleNotFoundError Missing package pip install

CORS Error Frontend blocked Add CORS headers


DEBUGGING TECHNIQUES

1. Print Debugging
print("Data received:", [Link])
2. Use Terminal Logs
Error in [Link] line 10
3. Django Debug Mode
DEBUG = True
DEPLOYMENT OVERVIEW

• Making your API available on the internet.


• Production deployment requires a web server and
application server.
• When deploying to Render, Gunicorn works because
Render uses Linux servers.
• The Start Command in Render should be:
• gunicorn [Link]:application
DEPLOY ON RENDER

Render is one of the easiest ways to deploy a Django REST API


publicly for free. It works very well for projects built with
Django and
Django REST Framework.
Your Computer

GitHub Repository

Render Cloud

Public API URL
DEPLOYMENT SETUP FOR A
DJANGO REST API ON RENDER
1. [Link]
• Create a file [Link] in the project root.
#!/usr/bin/env bash
pip install -r [Link]
python [Link] collectstatic --noinput
python [Link] migrate

When Render deploys the project, it runs this script automatically.


2. Procfile
• Create a file named Procfile (no extension).
web: gunicorn [Link]:application
It tells Render how to start the server.
3. [Link]
asgiref==3.11.0
Django==5.0.4
djangorestframework==3.15.1
gunicorn==21.2.0
packaging==26.0
pillow==12.1.0
psycopg2-binary==2.9.9
sqlparse==0.5.4
tzdata==2025.3
whitenoise==6.6.0
DEPLOYMENT FLOW
GitHub

Render detects Django project

[Link] installs packages

[Link] runs migrations

Procfile starts Gunicorn

Django API goes live


Step 1 — Create a GitHub Repository
Render deploys projects from GitHub.
Create a repository on
GitHub.
Then upload your project.

Inside your project folder run:


git init
git add .
git commit -m "Initial commit“

Connect to GitHub:
git remote add origin [Link]
git push -u origin main

Step 2 — Create [Link]


Render installs dependencies from this file.
Run:
pip freeze > [Link]
Commit again:
git add [Link]
git commit -m "Add requirements"
git push
Step 3 — Create [Link]
Create file:
[Link]
Add:
#!/usr/bin/env bash
pip install -r [Link]
python [Link] collectstatic --noinput
python [Link] migrate

Step 4 — Update [Link]


Add Render host.

ALLOWED_HOSTS = [‘*’]

Commit changes:
git add .
git commit -m "Prepare for deployment"
git push

Step 5 — Create Render Account


Go to
[Link]
Sign up using GitHub.
Step 6 — Create a New Web Service
On Render dashboard:
New → Web Service
Connect your GitHub repository.

Step 7 — Configure Deployment


Fill in:
Name
book-api
Runtime
Python 3
Build Command
pip install -r [Link]
Start Command
gunicorn [Link]:application
(Replace bookstore with your project name if different)

Step 8 — Deploy
Click
Create Web Service
Render will now:
Clone your repository
Install dependencies
Run migrations
Start your API server
This takes 2–5 minutes.
Step 9 — Access Your Public API

Render will generate a URL like:


[Link]

Your API endpoint:


[Link]
You can test it using:

•browser
•curl
•Postman

Example Response
[
{
"id":1,
"title":"Django Basics",
"author":"John Doe",
"price":500
}
]
GUNICORN

• Gunicorn is a Python WSGI HTTP server used to run


Django applications in production.
• Gunicorn handles:
Multiple users
High traffic
Worker processes
Load balancing
Install Gunicorn
pip install gunicorn

Test Gunicorn:
gunicorn [Link]

Open:
[Link]
Your API should still work.
NGINX

• Nginx acts as a reverse proxy and serves static files.


Role of Nginx :

Function Description

Reverse Proxy Sends request to Gunicorn

Static Files Serves images, CSS

Security Protects backend


Ubuntu / Linux:

sudo apt update


sudo apt install nginx

Start nginx:

sudo systemctl start nginx

Check:

[Link]

You should see Nginx welcome page.


Create Gunicorn Service
Create file:
/etc/systemd/system/[Link]
Example configuration:
[Unit]
Description=gunicorn daemon
After=[Link]

[Service]
User=ubuntu
Group=www-data
WorkingDirectory=/home/ubuntu/bookstore
ExecStart=/home/ubuntu/venv/bin/gunicorn \
--workers 3 \
--bind unix:/home/ubuntu/[Link] \
[Link]:application

[Install]
WantedBy=[Link]
Start service:
sudo systemctl start gunicorn
sudo systemctl enable gunicorn
Configure Nginx
Create file:
/etc/nginx/sites-available/bookstore
Example config:
server {
listen 80;

server_name your_server_ip;

location = /[Link] { access_log off; log_not_found off; }

location /static/ {
root /home/ubuntu/bookstore;
}

location / {
include proxy_params;
proxy_pass [Link]
}
}
Enable configuration:
sudo ln -s /etc/nginx/sites-available/bookstore /etc/nginx/sites-enabled
Test config:
sudo nginx -t
Restart nginx:
sudo systemctl restart nginx
Collect Static Files
python [Link] collectstatic

Final Result
Now your API should work at:
[Link]

Final Production Stack


Browser / Mobile App

Nginx

Gunicorn

Django REST Framework

Database
CLOUD DEPLOYMENT OPTIONS

• Popular platforms: Heroku and PythonAnywhere.


HEROKU
• Heroku is a cloud platform for deployment.

• Features

• Easy deployment
Free tier (limited)
Git-based deployment

• Required Files

Procfile
[Link]
[Link]

• Command

git push heroku main


PYTHON ANYWHERE

• PythonAnywhere is beginner-friendly hosting.


• Features
• Very easy UI
No DevOps needed
Good for students

• Steps
Upload code
Configure WSGI
Reload app
TYPICAL ARCHITECTURE

• Client → Nginx → Gunicorn → Django + DRF →


Database
COMPARISON TABLE

Tool Type Use

Gunicorn Server Run Django

Nginx Web Server Handle requests

Heroku Cloud Deploy app

PythonAnywhere Hosting Easy deployment


EXERCISE

• Create a Book API using Django REST Framework.


• Create a Movie Review API using Django REST
Framework.
• Create a Task Manager API using Django Rest
Framework.
• Create a Job Portal API using Django Rest Framework.
• Create a E-Commerce Order API using Django REST
Framework.
THANK YOU

Practice Makes Perfect

You might also like