- Python for Web Development
-
Overview
- Introduction to Flask and Django
- Setting Up a Flask Application
- Django Models and Migrations
- Routing and URL Handling in Django and Flask
- Forms and User Authentication in Django and Flask
- REST API Development with Flask & Django
- Working with Databases (SQLite, PostgreSQL, MySQL)
- Template Engines (Jinja2 for Flask, Django Templates)
- Deployment of Flask & Django Applications on AWS, GCP, and Heroku
- Security Best Practices for Web Apps
REST API Development with Flask & Django
APIs (Application Programming Interfaces) allow communication between different applications. REST (Representational State Transfer) is a widely used architecture for building APIs. In this tutorial, we’ll explore how to develop REST APIs using both Flask and Django.
1. REST API in Django (Using Django REST Framework - DRF)
Django provides Django REST Framework (DRF), a powerful toolkit for building APIs.
Installing DRF
Run the following command:
pip install djangorestframework
Adding DRF to Installed Apps
In settings.py
:
INSTALLED_APPS = [
'rest_framework',
'myapp', # Your Django app
]
Creating a Simple API
Let’s create a simple Todo API to list, create, update, and delete tasks.
1. Define a Model (models.py)
from django.db import models
class Todo(models.Model):
title = models.CharField(max_length=255)
completed = models.BooleanField(default=False)
def __str__(self):
return self.title
2. Create a Serializer (serializers.py)
from rest_framework import serializers
from .models import Todo
class TodoSerializer(serializers.ModelSerializer):
class Meta:
model = Todo
fields = '__all__'
3. Create API Views (views.py)
from rest_framework import generics
from .models import Todo
from .serializers import TodoSerializer
class TodoListCreateView(generics.ListCreateAPIView):
queryset = Todo.objects.all()
serializer_class = TodoSerializer
class TodoRetrieveUpdateDeleteView(generics.RetrieveUpdateDestroyAPIView):
queryset = Todo.objects.all()
serializer_class = TodoSerializer
4. Define API Routes (urls.py)
from django.urls import path
from .views import TodoListCreateView, TodoRetrieveUpdateDeleteView
urlpatterns = [
path('api/todos/', TodoListCreateView.as_view(), name='todo-list-create'),
path('api/todos/<int:pk>/', TodoRetrieveUpdateDeleteView.as_view(), name='todo-detail'),
]
5. Run Migrations
python manage.py makemigrations
python manage.py migrate
6. Start Django Server
python manage.py runserver
7. Test API
Use Postman or curl to test the API:
curl -X GET http://127.0.0.1:8000/api/todos/
Django REST Framework makes it easy to create APIs using serializers and generic views.
2. REST API in Flask (Using Flask-RESTful)
Flask doesn’t have built-in API support like Django, but we can use Flask-RESTful.
Installing Flask-RESTful
Run:
pip install flask flask-restful
Creating a Simple API
Let’s create the same Todo API in Flask.
1. Setup Flask App
Create app.py
:
from flask import Flask, request
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
todos = {}
class Todo(Resource):
def get(self, todo_id):
return {todo_id: todos.get(todo_id, "Not found")}
def post(self, todo_id):
todos[todo_id] = request.json['task']
return {todo_id: todos[todo_id]}
def put(self, todo_id):
todos[todo_id] = request.json['task']
return {todo_id: todos[todo_id]}
def delete(self, todo_id):
if todo_id in todos:
del todos[todo_id]
return {'message': 'Deleted'}
return {'message': 'Not found'}, 404
api.add_resource(Todo, '/api/todos/<string:todo_id>')
if __name__ == '__main__':
app.run(debug=True)
2. Start Flask Server
python app.py
3. Test API
- Create a new task:
curl -X POST -H "Content-Type: application/json" -d '{"task": "Learn Flask"}' http://127.0.0.1:5000/api/todos/1
- Get a task:
curl -X GET http://127.0.0.1:5000/api/todos/1
- Update a task:
curl -X PUT -H "Content-Type: application/json" -d '{"task": "Learn Django"}' http://127.0.0.1:5000/api/todos/1
- Delete a task:
curl -X DELETE http://127.0.0.1:5000/api/todos/1
Flask-RESTful provides a lightweight way to create APIs with minimal setup.
3. Comparing Django REST Framework vs Flask-RESTful
Feature | Django REST Framework (DRF) | Flask-RESTful |
---|---|---|
Ease of Use | Easier for large apps | Simpler for small apps |
Performance | Slightly slower | Faster for small APIs |
Features | Built-in authentication, pagination, permissions | Lightweight and customizable |
Best for | Full-stack Django apps | Microservices, small APIs |
Use Django REST Framework if you need a full-featured API with authentication, permissions, and ORM support.
Use Flask-RESTful for lightweight APIs or microservices.
Conclusion
We explored how to build REST APIs using Django REST Framework and Flask-RESTful.
- Django REST Framework is great for full-featured APIs with authentication.
- Flask-RESTful is perfect for lightweight, flexible APIs.
Prepare for Interview
- Debugging in Python
- Multithreading and Multiprocessing in Python
- Context Managers in Python
- Decorators in Python
- Generators in Python
- Requests in Python
- Django
- Flask
- Matplotlib/Seaborn
- Pandas
- NumPy
- Modules and Packages in Python
- File Handling in Python
- Error Handling and Exceptions in Python
- Indexing and Performance Optimization in SQL
Random Blogs
- Convert RBG Image to Gray Scale Image Using CV2
- Generative AI - The Future of Artificial Intelligence
- Career Guide: Natural Language Processing (NLP)
- The Ultimate Guide to Data Science: Everything You Need to Know
- Big Data: The Future of Data-Driven Decision Making
- The Ultimate Guide to Artificial Intelligence (AI) for Beginners
- Deep Learning (DL): The Core of Modern AI
- Ideas for Content of Every niche on Reader’s Demand during COVID-19
- Best Platform to Learn Digital Marketing in Free
- Data Analytics: The Power of Data-Driven Decision Making
- 10 Awesome Data Science Blogs To Check Out
- 5 Ways Use Jupyter Notebook Online Free of Cost
- Top 10 Blogs of Digital Marketing you Must Follow
- Important Mistakes to Avoid While Advertising on Facebook
- Top 10 Knowledge for Machine Learning & Data Science Students
Datasets for Machine Learning
- Ozone Level Detection Dataset
- Bank Transaction Fraud Detection
- YouTube Trending Video Dataset (updated daily)
- Covid-19 Case Surveillance Public Use Dataset
- US Election 2020
- Forest Fires Dataset
- Mobile Robots Dataset
- Safety Helmet Detection
- All Space Missions from 1957
- OSIC Pulmonary Fibrosis Progression Dataset
- Wine Quality Dataset
- Google Audio Dataset
- Iris flower dataset
- Artificial Characters Dataset
- Bitcoin Heist Ransomware Address Dataset