Django Web Framework (MTV Pattern)- Focuses on building a complete web
application with Django MTV pattern - creating models, views, templates and
admin interface to display IoT weather data in a browser dashboard.
Django REST API Framework - Focuses on building a REST API using Django REST
Framework - creating serializers, viewsets and routers to let external apps
(mobile, web, devices) access the same IoT data through HTTP requests.
PART 3: REST APIs FOR IOT
Step 1: What is a Web API?
Say this: "Imagine you have a weather app on your phone and a dashboard on
your computer. Both need the same temperature data. Do you build two
separate systems? No - you build ONE API that both can use."
Simple Definition:
API = A waiter in a restaurant
You (app) tell the waiter what you want
Waiter goes to kitchen (server) and brings back your food (data)
Key Point: API lets different software talk to each other using the internet
Step 2: What is REST?
Say this: "REST is just a set of rules for building APIs - like traffic rules for the
internet."
Simple Breakdown:
REpresentational = Data is presented in a format (usually JSON)
State = Current situation/data
Transfer = Moving data between client and server
Analogy: REST is like ordering at a restaurant:
You ask for what you want (request)
Kitchen prepares it (process)
Waiter brings it to you (response)
Every time you order, it's a new interaction (stateless)
Step 3: REST Principles - Made Simple
Four Simple Rules:
Principle Simple Meaning
Stateless Server doesn't remember past requests. Each request stands alone
Client-Server Phone app (client) and database (server) are separate
Uniform Interface All resources are accessed the same way
Resource-Based Everything is a "thing" you can access (like /sensors, /stations)
Stateless Analogy: Like ordering at a coffee shop - they don't remember what
you ordered last week. You tell them again each time.
Step 4: HTTP Methods - The Action Words
Show this table:
Method What it does Restaurant Analogy
GET Retrieve data "What's on the menu?"
POST Create new "I'd like to order a new dish"
PUT/PATCH Update existing "Can you change my order?"
DELETE Remove "Cancel my order"
Simple Summary: GET = read, POST = add, PUT = update, DELETE = remove
Step 5: Why REST for IoT?
Say this: "IoT is all about devices talking to each other. REST gives them a
common language."
Real Scenario:
Temperature sensor sends data → REST API → Cloud database
Your phone app → REST API → Gets that data
Your web dashboard → REST API → Gets same data
Benefit: One API serves everyone!
Step 6: Introducing Django REST Framework (DRF)
Say this: "Django REST Framework is like Django but specifically for building
APIs. It does all the heavy lifting for us."
Install:
bash
pip install djangorestframework markdown django-filter
What it gives you:
Serializers (convert data to JSON)
Authentication (security)
Browsable API (test your API in browser)
Step 7: Our Weather Station API
What we're building: An API for weather station data
Resource: Station
Data fields:
name (City name)
timestamp (When reading was taken)
temperature (Current temp)
lat/lon (Location)
Operations: Create, Read, Update, Delete (CRUD)
Step 8: Step 1 - Define the Model
In [Link]:
python
class Station([Link]):
name = [Link](max_length=10)
timestamp = [Link](max_length=10)
temperature = [Link](max_length=5)
lat = [Link](max_length=10)
lon = [Link](max_length=10)
Explain: "This defines what a 'Station' looks like in our database. Each field is a
piece of data we want to store."
Step 9: Step 2 - Create a Serializer
In [Link]:
python
class StationSerializer([Link]):
class Meta:
model = Station
fields = ('url', 'name', 'timestamp', 'temperature', 'lat', 'lon')
Simple Explanation: "A serializer converts Python data to JSON (the format
APIs use). Think of it as a translator - Python ↔ JSON."
Analogy: Like converting a letter from English to Spanish so someone else can
read it.
Step 10: Step 3 - Create a ViewSet
In [Link]:
python
class StationViewSet([Link]):
queryset = [Link]()
serializer_class = StationSerializer
Breakdown:
queryset = All station data from database
serializer_class = How to convert that data to JSON
ModelViewSet = Automatically gives us GET, POST, PUT, DELETE - all 4
operations with just 3 lines!
Say this: "With just 3 lines of code, we get a complete API!"
Step 11: Step 4 - Configure URLs with Router
In [Link]:
python
router = [Link]()
[Link](r'station', [Link])
urlpatterns = [
path('', include([Link])),
# ... other URLs
]
Explain: "Router automatically creates all the URL patterns for us:"
/station/ → List all stations (GET) or create new (POST)
/station/1/ → Get, update, or delete station with ID 1
Step 12: Step 5 - Configure Settings
In [Link]:
python
INSTALLED_APPS = [
# ...
'rest_framework',
]
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [],
'DEFAULT_PAGINATION_CLASS':
'rest_framework.[Link]',
'PAGE_SIZE': 10
}
Say this: "We just tell Django to include REST Framework and set some basic
options."
Step 13: Run and Test the API
bash
python [Link] makemigrations
python [Link] migrate
python [Link] runserver
Visit: [Link]
Show the browsable API: "Look - Django REST Framework gives us a web
interface to test our API. We can see all stations and even create new ones right
here!"
Step 14: Interact with API using CURL
Create a new station (POST):
bash
curl -X POST -d '{"name":"Chennai", "temperature":"32", "lat":"13.08",
"lon":"80.27"}' -H "Content-Type: application/json" [Link]
Get all stations (GET):
bash
curl [Link]
Get one station (GET):
bash
curl [Link]
Update a station (PUT):
bash
curl -X PUT -d '{"name":"Chennai", "temperature":"33", "lat":"13.08",
"lon":"80.27"}' -H "Content-Type: application/json"
[Link]
Delete a station (DELETE):
bash
curl -X DELETE [Link]
Step 15: Front-end Consuming the API
In [Link] (for your web page):
python
import requests
from [Link] import render
def home(request):
# Call our own API
response = [Link]('[Link]
stations = [Link]()
return render(request, '[Link]', {'stations': stations})
Explain: "Our web page doesn't talk to the database directly anymore. It talks to
our API. This means we could replace the database tomorrow and our web page
still works!"
Step 16: The Big Picture - Benefits
Draw this diagram:
text
┌─────────────┐
│ Sensor │
│ (Device) │
└──────┬──────┘
│ POST data
▼
┌─────────────┐ ┌─────────────┐
│ │────►│ Mobile │
│ REST API │ │ App │
│ │◄────│ │
└─────────────┘ └─────────────┘
▲
│
┌──────┴──────┐
│ Web Dashboard │
└─────────────┘
Three Big Benefits:
Benefit What it means
Separation Front-end and back-end are independent
Flexibility Same API serves web, mobile, and devices
Reusability Build once, use everywhere
QUICK SUMMARY
What We Built:
Component Purpose
Model Defines Station data structure
Serializer Converts Station ↔ JSON
ViewSet Handles all CRUD operations
Router Creates API URLs automatically
API Endpoints /station/ and /station/1/
HTTP Methods We Used:
Method URL Action
GET /station/ List all stations
GET /station/1/ Get station #1
Method URL Action
POST /station/ Create new station
PUT /station/1/ Update station #1
DELETE /station/1/ Delete station #1
KEY TAKEAWAYS
1. REST is just rules for how apps should talk to each other
2. HTTP methods are simple actions (GET, POST, PUT, DELETE)
3. Django REST Framework does the heavy lifting
4. One API can serve websites, mobile apps, and IoT devices
5. Separation means you can change the back-end without breaking the
front-end