๐งฉ 1. What Is an API?
An API allows software systems to communicate with each other.
In web development, APIs typically use HTTP to send and receive data (usually in JSON format).
For example, a client might make a request like:
GET /api/users/1
and receive a JSON response:
{
"id": 1,
"name": "Alice"
}
⚙️ 2. Choosing a Python Framework for APIs
There are several Python frameworks for building APIs. The most popular ones include:
Framework Description Ideal Use Case
Flask Lightweight and flexible. Easy to start with. Small to medium APIs, microservices
FastAPI Modern, fast (ASGI), supports async, auto-generates docs. Modern APIs with async support
Django REST Framework (DRF) Built on Django. Full-featured and robust. Large, enterprise-grade APIs
๐ 3. Example 1 — Building a REST API with Flask
๐ฆ Install Flask
pip install flask
๐ง Basic Flask API
from flask import Flask, jsonify, request
app = Flask(__name__)
# Mock database
users = [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]
@app.route("/api/users", methods=["GET"])
def get_users():
return jsonify(users)
@app.route("/api/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 ("User not found", 404)
@app.route("/api/users", methods=["POST"])
def create_user():
data = request.get_json()
new_user = {"id": len(users) + 1, "name": data["name"]}
users.append(new_user)
return jsonify(new_user), 201
if __name__ == "__main__":
app.run(debug=True)
✅ Test it
Start the server and send requests using:
curl:
curl http://127.0.0.1:5000/api/users
Postman or Thunder Client (VS Code extension)
⚡ 4. Example 2 — Building an API with FastAPI
FastAPI is a modern framework that’s both fast and developer-friendly.
๐ฆ Install FastAPI and Uvicorn
pip install fastapi uvicorn
๐ง Basic FastAPI App
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
id: int
name: str
users = [User(id=1, name="Alice"), User(id=2, name="Bob")]
@app.get("/api/users")
def get_users():
return users
@app.post("/api/users")
def create_user(user: User):
users.append(user)
return user
๐ Run the API
uvicorn main:app --reload
Visit:
API docs: http://127.0.0.1:8000/docs
Redoc UI: http://127.0.0.1:8000/redoc
๐ก FastAPI automatically generates OpenAPI (Swagger) documentation!
๐งฑ 5. Example 3 — API with Django REST Framework (DRF)
For larger applications, DRF is a powerful option.
๐ฆ Install Django + DRF
pip install django djangorestframework
๐️ Setup
django-admin startproject myproject
cd myproject
python manage.py startapp api
⚙️ Add to settings.py
INSTALLED_APPS = [
'rest_framework',
'api',
]
๐ Define a Model (api/models.py)
from django.db import models
class User(models.Model):
name = models.CharField(max_length=100)
๐ Create a Serializer (api/serializers.py)
from rest_framework import serializers
from .models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
๐ Define Views (api/views.py)
from rest_framework import viewsets
from .models import User
from .serializers import UserSerializer
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
๐ Add URLs (api/urls.py)
from rest_framework import routers
from .views import UserViewSet
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
urlpatterns = router.urls
๐ Include in project urls.py
from django.urls import path, include
urlpatterns = [
path('api/', include('api.urls')),
]
Run:
python manage.py migrate
python manage.py runserver
Visit:
http://127.0.0.1:8000/api/users/
๐ 6. Securing Your API
Use HTTPS (TLS)
Always serve your API over HTTPS to protect data in transit.
Authentication & Authorization
JWT (JSON Web Token) — e.g., PyJWT or FastAPI’s OAuth2PasswordBearer
OAuth2 — for third-party logins (Google, GitHub, etc.)
API Keys — simple token-based authentication
Example (FastAPI JWT auth):
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
def get_current_user(token: str = Depends(oauth2_scheme)):
if token != "mysecrettoken":
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED)
return {"user": "authorized_user"}
Rate Limiting
Use middleware like Flask-Limiter or API gateways (NGINX, Cloudflare).
Input Validation
FastAPI’s pydantic and DRF’s serializers make validation simple.
๐️ 7. Connecting to a Database
Common libraries:
SQLAlchemy — ORM for SQL databases
Tortoise ORM — async ORM for FastAPI
Django ORM — built-in with Django
Example (Flask + SQLAlchemy):
pip install flask_sqlalchemy
from flask_sqlalchemy import SQLAlchemy
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80))
๐งฐ 8. Testing Your API
Pytest for unit testing.
HTTPX or requests for integration tests.
Example:
import requests
def test_get_users():
response = requests.get("http://127.0.0.1:8000/api/users")
assert response.status_code == 200
☁️ 9. Deploying Your API
Deployment options:
Docker containers (recommended for portability)
Cloud platforms like AWS, Azure, Google Cloud
PaaS options like Render, Heroku, or Railway
Example Dockerfile
FROM python:3.12
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
✅ 10. Best Practices Summary
Area Best Practice
Security Use HTTPS, JWT, validate input
Documentation Use OpenAPI/Swagger
Error Handling Return proper HTTP status codes
Versioning Prefix endpoints (e.g., /api/v1/)
Testing Automate tests before deployment
Performance Use async, caching, and pagination
Learn Fullstack Python Training in Hyderabad
Read More
Encrypting Sensitive Data in Full Stack Python Apps
Common Web Security Vulnerabilities and How to Protect Against Them
Encrypting Sensitive Data in Full Stack Python Apps
At Our Quality Thought Training Institute in Hyderabad
Subscribe by Email
Follow Updates Articles from This Blog via Email
No Comments