APIs with Python (Flask/Django)

Why Use Flask or Django for APIs?

  1. Flask:
    • Lightweight and flexible.
    • Ideal for building simple or microservice-based APIs.
    • Minimal setup with full control over components.
  2. Django:
    • Feature-rich and scalable.
    • Best suited for large-scale applications.
    • Comes with a built-in ORM, authentication, and admin interface.

Both frameworks allow developers to create RESTful APIs, which use HTTP methods (GET, POST, PUT, DELETE) to perform CRUD operations.

Creating APIs with Flask

Flask is a microframework that provides the core tools to build APIs quickly. Developers can extend it with libraries like Flask-RESTful or Flask-SQLAlchemy.

Step-by-Step Guide to Building an API with Flask

Install Flask:

pip install flask

Basic Flask API Example:

from flask import Flask, jsonify, request

app = Flask(__name__)

# Sample data
users = [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"}
]

# Route to get all users
@app.route('/users', methods=['GET'])
def get_users():
return jsonify(users)

# Route to get a specific user by ID
@app.route('/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
user = next((u for u in users if u['id'] == user_id), None)
return jsonify(user) if user else {"error": "User not found"}, 404

# Route to add a new user
@app.route('/users', methods=['POST'])
def add_user():
new_user = request.json
users.append(new_user)
return jsonify(new_user), 201

if __name__ == '__main__':
app.run(debug=True)

Explanation:

  • GET /users: Fetches all users.
  • GET /users/<id>: Retrieves a specific user by ID.
  • POST /users: Adds a new user to the list.

Run the code and test the endpoints using tools like Postman or curl.

Creating APIs with Django

Django is a full-stack framework with built-in tools for rapid development. To create APIs, Django REST Framework (DRF) is often used.

Step-by-Step Guide to Building an API with Django

Install Django and Django REST Framework:

pip install django djangorestframework

Create a New Django Project:

django-admin startproject myproject
cd myproject

Create an App:

python manage.py startapp myapp

Set Up Models: Define the data structure in models.py.

from django.db import models

class User(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(unique=True)

def __str__(self):
return self.name

Create a Serializer: Serializers convert model instances to JSON.

from rest_framework import serializers
from .models import User

class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'

Create Views: Define API endpoints in views.py.

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import User
from .serializers import UserSerializer

class UserList(APIView):
def get(self, request):
users = User.objects.all()
serializer = UserSerializer(users, many=True)
return Response(serializer.data)

def post(self, request):
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Set Up URLs: Map the views to URLs in urls.py.

from django.urls import path
from .views import UserList

urlpatterns = [
path('users/', UserList.as_view(), name='user-list'),
]

Apply Migrations:

python manage.py makemigrations
python manage.py migrate

Run the Server:

python manage.py runserver

Testing the API:

  • Use /users/ endpoint for GET and POST operations.

Flask vs Django for APIs

FeatureFlaskDjango REST Framework
Learning CurveEasier for beginnersSteeper, requires Django knowledge
FlexibilityHighly flexibleMore structured
PerformanceLightweight and fasterHeavier but robust
Use CaseSmall to medium projectsLarge, complex projects

Leave a Comment

BoxofLearn