PyVerse Lesson: Creating Your First Web Server
Overview
Welcome to the web side of Python! In this lesson, you'll build your very first web server. A web server is a program that listens for requests from a web browser and sends back responses like web pages, messages, or data. By the end, you'll be able to open your browser and see a page served by your own Python code.
Learning Goals
By the end of this lesson, you will be able to:
- Explain what a web server is in simple terms.
- Run a very quick local server to share files.
- Create a tiny Python web server using Flask.
- Add simple routes that return text, HTML, and JSON.
- Fix common beginner errors.
What You Need
- A computer with Python 3.8+ installed
- A code editor (VS Code, Thonny, IDLE, or any editor you like)
- Internet access to install one small package (Flask)
- A web browser (Chrome, Edge, Firefox, or Safari)
Tip:
To check Python is installed, open your terminal (Command Prompt on Windows, Terminal on macOS/Linux) and type:
python --version- If that doesn't work:
- On Windows try:
py --version - On macOS/Linux try:
python3 --version
- On Windows try:
Key Words (Simple Definitions)
- Server: A program that listens and responds to browser requests.
- Client: The browser or app that asks the server for something.
- Request: The message sent by the client (like "Please show me the home page.").
- Response: The message sent back by the server (like "Here's your page!").
- Route: The path in the URL (like / or /hello) that tells the server what to do.
- Localhost: Your own computer acting like a server (address 127.0.0.1).
Safety Note
You'll run your server only on your own computer (localhost). This is safe for learning. Do not share your port or try to put this on the public internet yet.
Part A: The 2-Minute Server (No Python Code)
This is the fastest way to see something at http://localhost using Python's built-in file server. It serves files from a folder on your computer.
Steps:
- Make a new folder on your desktop named
my_site. - Inside
my_site, create a file namedindex.htmlwith this content:<!doctype html> <html> <head><meta charset="utf-8"><title>My First Site</title></head> <body> <h1>Hello from my computer!</h1> <p>This page is being served by Python's built-in server.</p> </body> </html> - Open your terminal, go into the folder, and start the server:
- Windows:
cd Desktop\my_site python -m http.server 8000(If python doesn't work, try:
py -m http.server 8000) - macOS/Linux:
cd ~/Desktop/my_site python3 -m http.server 8000
- Windows:
- Open your browser and go to:
http://127.0.0.1:8000 - To stop the server, go back to the terminal and press
Ctrl + C.
What just happened?
Your computer acted like a tiny web server that simply shares the files in my_site. Great for static pages. Next, let's build a "smart" server that runs Python code and can respond differently based on the URL.
Part B: Your First Python Web Server with Flask
We'll use Flask, a small and friendly Python library for web servers.
Step 1: Create a project folder
- Make a folder named
pyverse_serveranywhere you like.
Optional but nice: create a virtual environment
(you can skip this if it feels confusing).
Windows:
python -m venv .venv
.venv\Scripts\activatemacOS/Linux:
python3 -m venv .venv
source .venv/bin/activateStep 2: Install Flask
Windows:
pip install flask(If that fails, try: py -m pip install flask)
macOS/Linux:
pip3 install flask(Or: python3 -m pip install flask)
Step 3: Create app.py
Open your editor and make a file named app.py with this code:
from flask import Flask, request
app = Flask(__name__)
# Route: Home page
@app.route("/")
def home():
return "Hello, Web!
Your first Flask server is running.
"
# Route: Say hello to a name in the URL, e.g., /hello/Alex
@app.route("/hello/<name>")
def hello(name):
return f"Hello, {name.capitalize()}!"
# Route: Simple API that returns the current time as JSON
@app.route("/api/time")
def api_time():
from datetime import datetime
return {"time": datetime.now().strftime("%H:%M:%S")}
# Route: Use a query parameter, e.g., /greet?name=Sky
@app.route("/greet")
def greet():
name = request.args.get("name", "friend")
return f"Hi, {name}!"
if __name__ == "__main__":
app.run(debug=True)What this does:
app = Flask(__name__)creates a web app.@app.route("/")listens for visits to the home page.- Each function returns what the browser should show.
debug=Truelets you make changes and auto-reload the server.
Step 4: Run the server
- In your terminal, go to the
pyverse_serverfolder and run:- Windows:
python app.py(or:py app.py) - macOS/Linux:
python3 app.py
- Windows:
- Open your browser to:
http://127.0.0.1:5000
Try these pages:
- Home:
http://127.0.0.1:5000/ - Hello route:
http://127.0.0.1:5000/hello/Alex - API time:
http://127.0.0.1:5000/api/time - Greet with a name:
http://127.0.0.1:5000/greet?name=Sky
To stop the server, press Ctrl + C in the terminal.
Step 5 (Optional): Use a simple HTML template
Flask can render full HTML files from a folder named templates.
- Make a folder named
templatesnext toapp.py. - Inside
templates, create a file namedhome.htmlwith this content:<!doctype html> <html> <head> <meta charset="utf-8"> <title>PyVerse Server</title> <style> body { font-family: Arial, sans-serif; margin: 2rem; } .tip { color: #2d6cdf; font-weight: bold; } a { color: #1b7bd4; } </style> </head> <body> <h1>Welcome to your first web server</h1> <p>Today's tip: <span class="tip">{{ tip }}</span></p> <p>Try: <a href="/hello/Alex">/hello/Alex</a> | <a href="/api/time">/api/time</a></p> </body> </html> - Update
app.pyto render the template on the home route:from flask import Flask, request, render_template from datetime import datetime app = Flask(__name__) @app.route("/") def home(): return render_template("home.html", tip="Keep it simple!") @app.route("/hello/<name>") def hello(name): return f"Hello, {name.capitalize()}!" @app.route("/api/time") def api_time(): return {"time": datetime.now().strftime("%H:%M:%S")} @app.route("/greet") def greet(): name = request.args.get("name", "friend") return f"Hi, {name}!" if __name__ == "__main__": app.run(debug=True)
Refresh http://127.0.0.1:5000 and you'll see your styled page with a tip and helpful links.
How It Works (Short and Sweet)
- Your browser sends a request to your server (like asking a question).
- Flask finds the matching route function for that URL.
- Flask runs your Python function and returns a response (text, HTML, or JSON).
- The browser shows the response.
Common Errors and Quick Fixes
- ModuleNotFoundError: No module named 'flask'
Fix: Install Flask. Try one of these:
pip install flask py -m pip install flask python3 -m pip install flask - Address already in use or Port in use
Fix: An old server is still running. Stop it (Ctrl + C) or change the port:
app.run(debug=True, port=5001) - TemplateNotFound: home.html
Fix: The file must be in a folder named
templates(exact name) next toapp.py. - Page not found (404)
Fix: Check the route spelling. For example,
/hello/Alexis different from/hello/alex(but our code handles the name either way). - SyntaxError or IndentationError
Fix: Make sure parentheses, quotes, and indentation are correct. Keep code inside functions lined up neatly.
Challenges (Pick One)
- Easy: Add a new route
/aboutthat returns one sentence about you. - Medium: Make
/greetshow "Hi, name!" in a colorful HTML page instead of plain text. - Spicy: Add a route
/math/add?a=2&b=3that readsaandbfrom the query string and returns the sum.
Starter for the spicy challenge:
@app.route("/math/add")
def math_add():
a = int(request.args.get("a", 0))
b = int(request.args.get("b", 0))
return {"a": a, "b": b, "sum": a + b}Real-World Connection
Think of a restaurant:
- You (the client) order food (send a request).
- The kitchen (the server) receives the order, cooks it (runs the code), and brings your meal (the response).
- Different menu items are like different routes (
/,/hello,/api/time).
Troubleshooting Checklist
- Did you start the server (
python app.py) and keep the terminal open? - Are you visiting the right address (
http://127.0.0.1:5000)? - Did you install Flask successfully?
- Are your filenames and folders exact (
app.py,templates/home.html)? - Did you press
Ctrl + Cto stop the old server before starting a new one?
Wrap-Up
You just built your first web server! You served static files with Python's built-in server and created a dynamic Flask app with multiple routes. You learned how to return text, HTML, and JSON, and how to read information from the URL.
Next steps on PyVerse:
- Add forms so users can submit text to your server
- Serve images and CSS (static files)
- Use templates to reuse page layouts
- Save data to a simple database
Quick Reference (Copy-Paste Ready)
Basic Flask app:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello from Flask!"
if __name__ == "__main__":
app.run(debug=True)Run it:
- Windows:
python app.py(orpy app.py) - macOS/Linux:
python3 app.py
Visit in your browser:
http://127.0.0.1:5000
Stop the server:
Ctrl + C
Great job! Your computer just became a mini web server.