PYTHON PROGRAMMING:Day 21: Web Development Basics
Mastering day 21: web development basics concepts and implementation.
So far, every program you have written runs on your computer. You type input, Python processes it, and results appear in the terminal. That is powerful — but most software people use every day runs on the web: online stores, social media, banking apps, this very tutorial page.
Web development means building applications that communicate over the internet. Your Python code can become the "brain" behind a website — handling login, storing data, and sending pages back to users' browsers. You do not need to become a full-stack expert today, but understanding the basics opens a huge door.
Python is one of the most popular languages for web backends. Companies like Instagram, Pinterest, and Dropbox use Python web frameworks at massive scale. You will start with Flask — a small, friendly framework that lets you go from zero to a working web page in minutes.
What You Will Learn in This Chapter
By the end of this tutorial you will be able to:
- Explain how the web works (browser, server, HTTP)
- Understand what a web framework does and why Flask exists
- Create routes that respond to different URLs
- Return plain text, HTML, and JSON from Python functions
- Handle GET and POST requests
- Set up basic error handling for missing pages
- Know the difference between frontend and backend
- Understand CRUD and MVC at a high level
Estimated time: 60 minutes reading + 30 minutes practice
How the Web Works — The Big Picture
When you visit a website, two main players are involved:
- Client (browser) — Chrome, Firefox, Safari. Sends a request ("give me the home page").
- Server — A computer running your Python code. Processes the request and sends back a response (HTML, JSON, an image, etc.).
They communicate using HTTP (HyperText Transfer Protocol) — a set of rules for how requests and responses are formatted. Every URL you type, every form you submit, every API call — it is all HTTP underneath.
You type: https://schoolabe.com/courses/python
↓
Browser sends: GET /courses/python HTTP/1.1
↓
Server runs Python code → builds response
↓
Browser receives: HTML page → renders it on screen
Your job as a backend developer is to write the Python code on the server side — the part that decides what to send back for each request.
Frontend vs Backend
| Layer | What it is | Technologies | Your role today |
|---|---|---|---|
| **Frontend** | What the user sees and clicks | HTML, CSS, JavaScript | Brief exposure via templates |
| **Backend** | Logic, data, security | Python, Flask, databases | Main focus |
You can build a complete small app knowing mostly backend Python. The frontend can be as simple as a string of text or as rich as a full React application — Flask handles both.
What Is Flask?
Flask is a Python "micro-framework" for web development. "Micro" does not mean limited — it means Flask gives you the essentials (routing, request handling, templates) without forcing a specific project structure. You add what you need.
Install it once:
pip install flask
Then every Flask app follows the same skeleton:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Welcome to Python Web Development!"
if __name__ == '__main__':
app.run(debug=True)
Save this as app.py, run python app.py, and open http://localhost:5000 in your browser. You will see the welcome message. That is a live web server written in Python.
Output in the terminal:
* Running on http://127.0.0.1:5000
* Debug mode: on
Walkthrough:
Flask(__name__)creates the application object.@app.route('/')is a decorator — it tells Flask "when someone visits the root URL, call the function below."home()returns a string — Flask converts it into an HTTP response automatically.app.run(debug=True)starts a development server.debug=Truereloads the code when you save changes and shows helpful error pages.
Routes — Mapping URLs to Python Functions
A route connects a URL pattern to a Python function. Different URLs can run different logic:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Welcome to Python Web Development!"
@app.route('/about')
def about():
return "This site teaches Python step by step."
@app.route('/user/<name>')
def user(name):
return f"Hello, {name}!"
if __name__ == '__main__':
app.run(debug=True)
Try these URLs after starting the server:
http://localhost:5000/→ "Welcome to Python Web Development!"http://localhost:5000/about→ "This site teaches Python step by step."http://localhost:5000/user/Priya→ "Hello, Priya!"
The <name> part is a URL parameter — Flask captures whatever appears in that segment and passes it as an argument to your function. This is how dynamic pages work: one function handles every user profile, every product page, every blog post.
Returning JSON — Building API Endpoints
Web pages often need to exchange structured data, not just text. JSON (JavaScript Object Notation) is the standard format — and it maps naturally to Python dictionaries:
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/api/data', methods=['GET'])
def get_data():
return jsonify({
'message': 'This is a GET request',
'data': [1, 2, 3, 4, 5]
})
@app.route('/api/data', methods=['POST'])
def post_data():
data = request.get_json()
return jsonify({
'message': 'Data received successfully',
'received_data': data
})
if __name__ == '__main__':
app.run(debug=True)
GET /api/data returns a JSON object with a message and a list.
POST /api/data expects JSON in the request body and echoes it back.
jsonify() converts a Python dict into a JSON response with the correct Content-Type header. request.get_json() reads JSON sent by the client.
This pattern — URL + HTTP method → Python function → JSON response — is the foundation of REST APIs, which you will explore in depth on Day 22.
HTTP Methods — GET vs POST
| Method | Purpose | Example |
|---|---|---|
| **GET** | Retrieve data | Load a page, fetch a user profile |
| **POST** | Send/create data | Submit a form, create a new account |
| **PUT** | Update existing data | Edit a profile |
| **DELETE** | Remove data | Delete a post |
Flask lets you restrict a route to specific methods:
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'GET':
return "Show login form"
else:
username = request.form.get('username')
return f"Logging in as {username}"
For now, focus on GET (read) and POST (create/send). They cover most beginner web apps.
Templates — Dynamic HTML Pages
Returning plain strings works for learning, but real sites need HTML. Flask's template engine (Jinja2) lets you write HTML files with placeholders for Python data:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/users')
def list_users():
users = ['Priya', 'Marcus', 'Sofia']
return render_template('users.html', users=users)
Create a file templates/users.html:
<h1>User List</h1>
<ul>
{% for user in users %}
<li>{{ user }}</li>
{% endfor %}
</ul>
Flask looks for templates in a templates/ folder by default. The {% for %} and {{ user }} syntax injects your Python data into HTML. The browser receives a fully rendered page — it never sees the Python code.
CRUD — The Four Operations Every App Needs
Almost every web application performs the same four database operations:
- Create — add a new record (POST)
- Read — fetch existing records (GET)
- Update — modify a record (PUT/PATCH)
- Delete — remove a record (DELETE)
A blog app creates posts, reads them on the home page, updates drafts, and deletes old entries. A to-do app creates tasks, lists them, marks them done, and removes them. CRUD is the skeleton of most backend logic.
MVC — Organizing Your Code
Model-View-Controller (MVC) is a common pattern for structuring web apps:
- Model — data and business rules (Python classes, database tables)
- View — what the user sees (HTML templates)
- Controller — handles requests and connects Model to View (your Flask route functions)
Flask is flexible — it does not enforce MVC strictly, but thinking in these layers keeps projects maintainable as they grow.
A Complete Flask Application
Here is a fuller example combining routes, API endpoints, templates, and error handling:
# Install Flask: pip install flask
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
@app.route('/')
def home():
return "Welcome to Python Web Development!"
@app.route('/user/<name>')
def user(name):
return f"Hello, {name}!"
@app.route('/api/data', methods=['GET', 'POST'])
def api_data():
if request.method == 'GET':
return jsonify({
'message': 'This is a GET request',
'data': [1, 2, 3, 4, 5]
})
elif request.method == 'POST':
data = request.get_json()
return jsonify({
'message': 'Data received successfully',
'received_data': data
})
@app.route('/template')
def template_example():
users = ['Priya', 'Marcus', 'Sofia']
return render_template('users.html', users=users)
@app.errorhandler(404)
def not_found(error):
return jsonify({'error': 'Page not found'}), 404
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)
After running, try:
http://localhost:5000/— home pagehttp://localhost:5000/user/Priya— dynamic greetinghttp://localhost:5000/api/data— JSON APIhttp://localhost:5000/nonexistent— custom 404 error
The @app.errorhandler(404) decorator catches "page not found" requests and returns friendly JSON instead of Flask's default error page.
Other Python Web Frameworks (Quick Overview)
| Framework | Best for | Notes |
|---|---|---|
| **Flask** | Learning, small-to-medium apps | Minimal, you choose the structure |
| **Django** | Full-featured sites with admin panels | "Batteries included" — ORM, auth, admin built in |
| **FastAPI** | Modern APIs with automatic docs | Async support, type hints, very fast |
Start with Flask. Once you understand routes, requests, and responses, moving to Django or FastAPI is much easier because the core concepts are the same.
Common Mistakes
Mistake 1: Forgetting to install Flask
# Run this first
pip install flask
Without it, from flask import Flask raises ModuleNotFoundError.
Mistake 2: Running with debug=True in production
debug=True enables an interactive debugger that exposes your code to anyone who triggers an error. Great for development; never use it on a live public server.
Mistake 3: Wrong template folder location
Flask expects templates in a templates/ folder next to your app file. If render_template fails with TemplateNotFound, check the folder name and path.
Mistake 4: Not specifying methods on POST routes
# Browser GET requests will work; POST requests get "Method Not Allowed"
@app.route('/api/data')
# Correct — explicitly allow both
@app.route('/api/data', methods=['GET', 'POST'])
Mistake 5: Hardcoding localhost URLs
During development, localhost:5000 is fine. In production, use environment variables for host, port, and secret keys — never commit secrets to your code.
Practice Exercises
Exercise 1: Create a Flask app with three routes: / (home), /about (about page), and /contact (contact info). Return different text from each.
Exercise 2: Add a route /greet/<name> that returns "Good morning, <name>!" for any name in the URL.
Exercise 3: Create a /api/status endpoint that returns JSON with {"status": "ok", "version": "1.0"}.
Exercise 4: Add a 404 error handler that returns a custom HTML message instead of the default error page.
→ See all Python practice exercises with solutions
What Comes Next — Day 22: Working with APIs
Your Flask app can serve data to browsers. But modern apps also consume data from other services — weather APIs, payment gateways, social media feeds. Day 22 teaches you how to talk to those external APIs from Python.
Day 22 covers:
- What APIs are and how they work (the waiter analogy)
- Making GET and POST requests with the
requestslibrary - Parsing JSON responses
- Handling errors and rate limits
→ Continue to Day 22: Working with APIs
Chapter navigation
- Previous: Day 17: Basic Algorithms
- Next: Day 22: Working with APIs
- Python Quiz: Take the Python quiz
- All Python exercises: Explore Python exercises