Chapter 5: AI as a Service (Model → API using Django)
This chapter introduces one of the most important real-world AI concepts:
AI as a Service.
In production systems, AI models are not used directly — they are deployed as
services (APIs) that applications, websites, mobile apps, and systems can access.
Using Django, we build production-grade AI services that are scalable, secure, and enterprise-ready.
Real AI is not notebooks — it is API-driven system architecture.
⭐ What is AI as a Service?
- AI model runs on server
- Model exposed via API
- Systems send data
- AI processes input
- API returns prediction
⭐ AI Service Architecture (Django)
Client/App → Django API → AI Model → Decision Logic → JSON Response
⭐ Why Django for AI Services?
- Production security
- Scalable architecture
- User management
- API authentication
- Database integration
- Enterprise deployment
⭐ Basic Django AI API Example
Simple AI API using Django views:
# views.py
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
@csrf_exempt
def ai_predict(request):
if request.method == "POST":
data = json.loads(request.body)
value = data.get("value")
processed = value * 2 + 10
if processed > 100:
decision = "Approved"
else:
decision = "Review"
return JsonResponse({"decision": decision})
⭐ Django URL Mapping
# urls.py
from django.urls import path
from .views import ai_predict
urlpatterns = [
path("predict/", ai_predict),
]
⭐ Testing the API
POST /predict/
{
"value": 30
}
Response:
{
"decision": "Approved"
}
⭐ Model-Based Django AI Service
Serving a trained AI model using Django:
# views.py
import tensorflow as tf
import numpy as np
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
model = tf.keras.models.load_model("model.h5")
@csrf_exempt
def model_predict(request):
if request.method == "POST":
data = json.loads(request.body)
values = data.get("data")
arr = np.array(values).reshape(1, -1)
pred = model.predict(arr)[0][0]
return JsonResponse({"prediction": float(pred)})
⭐ AI Microservice Concept (Django)
- One AI service per app
- Modular AI architecture
- Independent deployment
- Scalable services
- Enterprise system design
⭐ AI Service Pipeline
Data → Django API → AI Model → Logic → API Response → System Action
⭐ Mini Practical Task
Build a Django AI API that:
- Accepts JSON input
- Processes data
- Applies AI logic
- Returns JSON output
# views.py
@csrf_exempt
def risk_api(request):
if request.method == "POST":
data = json.loads(request.body)
score = data.get("score")
risk = score * 3
if risk > 150:
result = "High Risk"
else:
result = "Low Risk"
return JsonResponse({"risk_level": result})
📌 Chapter Outcome
- Build AI services with Django
- Create AI APIs
- Deploy AI models as services
- Design AI microservices
- Integrate AI into real systems
📌 Core Principle
Models live in servers.
APIs bring AI to the world.
Django turns AI into enterprise systems.
