Django gives you a lot out of the box. Flask gives you a small core and lets you add only what you need, which makes it a good way to understand how web APIs work. Install it with pip install flask.
A first endpoint
from flask import Flask, jsonify, request
app = Flask(__name__)
courses = [{"id": 1, "title": "Python Full Stack"}]
@app.get("/api/courses")
def list_courses():
return jsonify(courses)
Run it with flask --app app run --debug and open http://127.0.0.1:5000/api/courses.
Reading one item, with a 404
@app.get("/api/courses/<int:course_id>")
def get_course(course_id):
for c in courses:
if c["id"] == course_id:
return jsonify(c)
return jsonify({"error": "Course not found"}), 404
Returning a tuple sets the HTTP status code.
Creating an item, with validation
@app.post("/api/courses")
def create_course():
data = request.get_json(silent=True) or {}
title = str(data.get("title", "")).strip()
if not title:
return jsonify({"error": "title is required"}), 400
course = {"id": len(courses) + 1, "title": title}
courses.append(course)
return jsonify(course), 201
Next steps to make it real
- A database: replace the list with SQLite or MySQL using SQLAlchemy.
- Blueprints: split routes into modules as the app grows.
- Tests: Flask’s test client sends fake requests in a few lines.
- Deployment: run with Gunicorn behind Nginx, never with the debug server.
Flask or Django?
Flask suits small APIs and learning how the pieces fit. Django suits larger apps that need an admin panel, authentication and an ORM from day one. Knowing both makes you a stronger Python developer.
Related: Django vs Flask, Django REST Framework and HTTP status codes.
These topics are practised with projects in our Python Full Stack course in Bangalore.
Book a free demo class at our BTM Layout centre, and ask a counsellor for batch details.
