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

FeatureDjango REST Framework (DRF)Flask-RESTful
Ease of UseEasier for large appsSimpler for small apps
PerformanceSlightly slowerFaster for small APIs
FeaturesBuilt-in authentication, pagination, permissionsLightweight and customizable
Best forFull-stack Django appsMicroservices, 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.