Python Backend Development (Django/FastAPI) for Mobile Apps
Imagine your mobile app has grown to 100,000 DAU, and the server can no longer handle peak loads. MongoDB clustering no longer helps—you need a fault-tolerant Python backend with sound architecture. Python is the second most popular language for mobile backends after Node.js, and we have two dominant options: Django REST Framework—batteries-included, ORM, admin, auth out of the box; FastAPI—asynchronous, type-safe, quick start. The choice depends on requirements for development speed, performance, and team size. Our engineers with extensive experience will help you decide and implement the project turnkey in 2–3 weeks (MVP) or 1–3 months (full backend). Contact us to discuss the details.
How to Choose Between Django REST Framework and FastAPI?
The key difference is the execution model and built-in features. FastAPI works asynchronously on asyncio from day one, offering high throughput for I/O-bound operations (network requests, database work). Django REST Framework has historically been synchronous, but since version 4.1 it supports async views via ASGI. If your project requires real-time features, WebSockets, or high concurrency, FastAPI is the obvious choice. If you need rapid development with an admin panel and rich ORM, DRF saves weeks.
FastAPI: When You Need Speed and Typing
FastAPI is built on Pydantic and Starlette. Each endpoint automatically validates input data via type annotations and generates OpenAPI documentation:
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from pydantic import BaseModel, UUID4
from sqlalchemy.ext.asyncio import AsyncSession
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/token")
class CreatePostRequest(BaseModel):
title: str
content: str
author_id: UUID4
class PostResponse(BaseModel):
id: UUID4
title: str
content: str
created_at: datetime
class Config:
from_attributes = True
@app.post("/posts", response_model=PostResponse, status_code=201)
async def create_post(
body: CreatePostRequest,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
):
if body.author_id != current_user.id:
raise HTTPException(status_code=403, detail="Forbidden")
post = await post_service.create(db, body)
return post
Pydantic v2 (Rust-based) validates data faster than most alternatives. response_model automatically serializes the ORM object and hides fields not in the schema (e.g., password hash won't appear in the response).
SQLAlchemy 2.x + AsyncSession for async work with PostgreSQL via asyncpg:
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
engine = create_async_engine(settings.DATABASE_URL) # postgresql+asyncpg://...
AsyncSessionLocal = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
async def get_db():
async with AsyncSessionLocal() as session:
yield session
Alembic for database schema migrations—generates diff between models and current DB.
JWT Authentication
from jose import JWTError, jwt
from datetime import datetime, timedelta
def create_access_token(user_id: str) -> str:
expires = datetime.utcnow() + timedelta(minutes=15)
return jwt.encode(
{"sub": user_id, "exp": expires, "type": "access"},
settings.JWT_SECRET,
algorithm="HS256",
)
async def get_current_user(
token: str = Depends(oauth2_scheme),
db: AsyncSession = Depends(get_db),
) -> User:
try:
payload = jwt.decode(token, settings.JWT_SECRET, algorithms=["HS256"])
user_id: str = payload.get("sub")
except JWTError:
raise HTTPException(status_code=401, detail="Could not validate token")
user = await user_repo.get(db, user_id)
if not user:
raise HTTPException(status_code=401, detail="User not found")
return user
Django REST Framework: When You Need a Full Stack
DRF wins when you need fast admin panel, rich ORM with select_related/prefetch_related, built-in permissions and throttling:
# serializers.py
class PostSerializer(serializers.ModelSerializer):
author_name = serializers.SerializerMethodField()
class Meta:
model = Post
fields = ['id', 'title', 'content', 'author_name', 'created_at']
read_only_fields = ['id', 'created_at']
def get_author_name(self, obj):
return obj.author.get_full_name()
# views.py
class PostViewSet(ModelViewSet):
serializer_class = PostSerializer
permission_classes = [IsAuthenticated]
throttle_classes = [UserRateThrottle]
def get_queryset(self):
return Post.objects.filter(author=self.request.user)\
.select_related('author')\
.order_by('-created_at')
select_related solves the N+1 problem: one SQL JOIN instead of a query per author. prefetch_related for many-to-many relationships.
django-channels for WebSocket (chat, realtime). Celery + Redis for background tasks (email sending, push notifications, heavy computations).
# tasks.py
from celery import shared_task
import firebase_admin.messaging as fcm
@shared_task(bind=True, max_retries=3, default_retry_delay=60)
def send_push_notification(self, token: str, title: str, body: str):
try:
message = fcm.Message(
token=token,
notification=fcm.Notification(title=title, body=body),
android=fcm.AndroidConfig(priority='high'),
apns=fcm.APNSConfig(payload=fcm.APNSPayload(aps=fcm.Aps(sound='default'))),
)
fcm.send(message)
except Exception as exc:
raise self.retry(exc=exc)
Comparison of Approaches
| Criteria | FastAPI | Django REST Framework |
|---|---|---|
| Async out of the box | Yes (asyncio) | Partial (Django 4.1+) |
| Startup speed | High | Medium |
| Admin panel | None (third-party) | Built-in |
| ORM | SQLAlchemy / Tortoise | Django ORM |
| API documentation | Auto-generated (Swagger) | drf-spectacular |
| Best suited for | New projects, API-only | Fast MVP with admin |
Typical Mistakes When Choosing Backend Architecture
- Ignoring real-time requirements: if the app needs real-time notifications, it's better to plan for WebSocket and an async framework from the start. Switching from synchronous Django to async mid-project is a costly migration.
- Underestimating microservice architecture: a monolith is enough at the start, but if you expect growth to 50+ endpoints, consider splitting into microservices. Python works well for microservices using FastAPI or Nameko.
- Lack of automatic API documentation: mobile developers spend hours aligning formats. OpenAPI (Swagger) solves this issue.
How to Ensure API Security?
In addition to JWT, we use CORS, rate limiting, input validation, and logging of suspicious activity. To protect against SQL injection, we use ORM with parameterized queries. All secrets are stored in Vault or AWS Secrets Manager. Dependencies are updated regularly.
For additional protection, we implement TOTP via pyotp and QR codes. This reduces account compromise risks by 99% (per OWASP).
Deployment
FastAPI or Django is launched via Uvicorn + Gunicorn with multiple workers. Docker with multi-stage builds for minimal images. Nginx as reverse proxy. PostgreSQL + Redis in docker-compose for local, RDS + ElastiCache for production. With this configuration, we guarantee 99.9% SLA and reduce infrastructure costs by up to 40% compared to monolithic approaches.
Stages of Backend Development
- Requirements analysis—study the technical specification, load, integrations. Estimate timeline.
- API design—OpenAPI specification, technology stack selection.
- Development—implement modules, configure database, authentication, background tasks.
- Testing—unit tests, integration tests, load tests (locust/k6).
- Deployment—Docker, CI/CD (GitHub Actions), monitoring (Prometheus + Grafana).
What's Included in the Development
- API design tailored to mobile client requirements
- PostgreSQL setup + Alembic migrations
- Auth (JWT)
- CRUD modules
- Push notifications (Firebase Admin SDK)
- Background tasks (Celery)
- Docker + CI/CD
- OpenAPI documentation
- Consultations at all stages
Timelines and Cost
MVP (Auth + 3–5 resources): 2 to 3 weeks. Full backend: 1 to 3 months. Cost is calculated individually after requirements analysis. Our engineers with experience from numerous projects guarantee quality and adherence to deadlines. Order turnkey backend development—get a consultation today.







