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.
Django provides Django REST Framework (DRF), a powerful toolkit for building APIs.
Run the following command:
pip install djangorestframeworkIn settings.py:
INSTALLED_APPS = [
'rest_framework',
'myapp', # Your Django app
]Let’s create a simple Todo API to list, create, update, and delete tasks.
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.titlefrom rest_framework import serializers
from .models import Todo
class TodoSerializer(serializers.ModelSerializer):
class Meta:
model = Todo
fields = '__all__'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 = TodoSerializerfrom 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'),
]python manage.py makemigrations
python manage.py migratepython manage.py runserverUse 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.
Flask doesn’t have built-in API support like Django, but we can use Flask-RESTful.
Run:
pip install flask flask-restfulLet’s create the same Todo API in Flask.
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)python app.pycurl -X POST -H "Content-Type: application/json" -d '{"task": "Learn Flask"}' http://127.0.0.1:5000/api/todos/1curl -X GET http://127.0.0.1:5000/api/todos/1curl -X PUT -H "Content-Type: application/json" -d '{"task": "Learn Django"}' http://127.0.0.1:5000/api/todos/1curl -X DELETE http://127.0.0.1:5000/api/todos/1Flask-RESTful provides a lightweight way to create APIs with minimal setup.
| 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.
We explored how to build REST APIs using Django REST Framework and Flask-RESTful.
Sign in to join the discussion and post comments.
Sign inPython Basics
Python is a powerful, high-level programming language known for its simplicity and versatility. It is widely used in various fields, including web development, data science, artificial intelligence, automation, and more. This tutorial series is designed to take you from the basics of Python to more advanced topics, ensuring a strong foundation in programming.
Object-Oriented Programming (OOP) in Python
Learn the fundamentals of Object-Oriented Programming (OOP) in Python, including classes, objects, inheritance, polymorphism, encapsulation, and more. Understand how OOP enhances code reusability, scalability, and organization.