PyVerse Lesson: Understanding Routes and HTTP Methods
Estimated time: 60–75 minutes
Tools: Python 3, Flask, a web browser (Chrome, Edge, Firefox), a terminal/command prompt
Lesson Goals
- Explain what a route is in a web app
- Understand what HTTP methods are (GET, POST, and a peek at PUT/DELETE)
- Create a simple Python web server with Flask
- Build routes that read information from the URL and from a form
- Test routes using your browser
Key Vocabulary
- Web server: A program that listens for web requests and sends back responses.
- Client: The thing that asks for web pages (usually your browser).
- URL: The website address (example: http://127.0.0.1:5000/hello/World).
- Path: The part of the URL after the domain (example: /hello/World).
- Route: A pattern your web app listens to, like /hello/<name>.
- HTTP: The set of rules for how browsers and servers talk.
- HTTP method: The action type in a request (GET, POST, PUT, DELETE).
- Query string: Extra info after a ? in the URL (example: ?term=pizza).
- Route parameter: A part of the path that acts like a variable (example: /hello/<name>).
Warm-Up (2 minutes)
Think of a library. You can:
- Read a book (GET information)
- Donate a book (POST new information)
- Update a book's details (PUT)
- Remove a book (DELETE)
Web servers do similar actions with routes and HTTP methods.
Part 1: What is a Route?
- A route is like a labeled door to your app. When you visit a URL, the server checks which door (route) matches and runs the code behind it.
- URL example:
http://127.0.0.1:5000/hello/World127.0.0.1:5000is your own computer at port 5000/hello/Worldis the path
- A route can include:
- Fixed parts:
/hello - Variables (route parameters):
/hello/<name> - Query string:
/search?term=pizza
- Fixed parts:
Part 2: HTTP Methods (Beginner-Friendly)
- GET: Ask for information (your browser does this when you visit a page).
- POST: Send new information (like submitting a form).
- PUT: Update something that already exists (more advanced; usually used by APIs).
- DELETE: Remove something (also typically used by APIs).
Today we will use GET and POST. We'll peek at PUT and DELETE for curiosity.
Setup (Step-by-Step)
- Check Python
- Open your terminal or command prompt and type:
python --version - If it shows Python 3.x, great. If not, install Python 3 from python.org.
- Open your terminal or command prompt and type:
- Make a project folder
- Create a new folder, for example:
routes_demo - Open the folder in your code editor (VS Code recommended).
- Create a new folder, for example:
- Install Flask
- In your terminal (inside the folder), run:
pip install flask
- In your terminal (inside the folder), run:
Build Your First Routes with Flask
Create a new file named app.py in your folder. Paste the code below.
File: app.py
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def home():
return '''
<h1>Welcome to PyVerse Routes Demo</h1>
<p>Try these:</p>
<ul>
<li><a href="/hello/World">/hello/World</a></li>
<li><a href="/search?term=pizza">/search?term=pizza</a> (query string)</li>
<li><a href="/message">/message</a> (send a message)</li>
</ul>
'''
@app.route('/hello/<name>')
def hello(name):
return f'Hello, {name}!'
@app.route('/search')
def search():
term = request.args.get('term', '')
if term:
return f'You searched for: {term}'
else:
return 'Please add ?term=something to the URL.'
@app.route('/message', methods=['GET', 'POST'])
def message():
if request.method == 'GET':
return '''
<h2>Send a Message</h2>
<form method="POST" action="/message">
<label>Your name: <input name="name"></label><br>
<label>Message: <input name="text"></label><br><br>
<button type="submit">Send</button>
</form>
'''
else:
name = request.form.get('name', 'Someone')
text = request.form.get('text', '')
if not text:
return 'Please include a message.', 400
return f'Thanks {name}! You said: {text}'
# Optional advanced demo for PUT and DELETE
@app.route('/items/<int:item_id>', methods=['PUT', 'DELETE'])
def items(item_id):
if request.method == 'PUT':
return f'Pretend we updated item {item_id}.', 200
else:
return f'Pretend we deleted item {item_id}.', 200
if __name__ == '__main__':
app.run(debug=True)Run and Test
- Start the server
- In the terminal, run:
python app.py - You should see something like: Running on http://127.0.0.1:5000
- In the terminal, run:
- Try the home route
- Open a browser and go to:
http://127.0.0.1:5000 - Click the example links.
- Open a browser and go to:
- Test a route parameter (/hello/<name>)
- Visit:
http://127.0.0.1:5000/hello/Alex - You should see: Hello, Alex!
- Visit:
- Test a query string (/search?term=...)
- Visit:
http://127.0.0.1:5000/search?term=chocolate - Try removing the term to see the message that asks for it.
- Visit:
- Test GET and POST on /message
- Visit:
http://127.0.0.1:5000/message - Fill in the form and press Send (this makes a POST request).
- You should see a thank-you message with what you typed.
- Visit:
Optional Advanced: Test PUT and DELETE (for curiosity)
Web forms usually only do GET and POST. To try PUT/DELETE, use curl (available on most systems).
Examples:
- Update (PUT):
curl -X PUT http://127.0.0.1:5000/items/3 - Delete (DELETE):
curl -X DELETE http://127.0.0.1:5000/items/3
You should see text responses like "Pretend we updated item 3."
How It Works (Simple Explanation)
@app.route('/path')connects a URL path to a Python function.request.methodtells you which HTTP method was used (GET, POST, etc.).request.argsgets query string values (from URLs like ?term=pizza).request.formgets data sent from a POST form.
Common Errors and How to Fix Them
- Error: ModuleNotFoundError: No module named 'flask'
Fix: Run
pip install flaskand then try again. - Page not found (404)
Fix: Check your route path carefully. For /hello/<name>, make sure you add a name in the URL, like /hello/Sam.
- Server already running or port in use
Fix: Close other servers or change the port:
app.run(debug=True, port=5001) - Nothing happens when I click
Fix: Ensure the server is running in the terminal and the URL is correct (http://127.0.0.1:5000).
- POST form says "Please include a message."
Fix: Make sure you typed something in the Message box.
Practice Challenges
Try one or more:
- Add a new route:
/bye/<name>that says "Goodbye, <name>!" - Add a
/repeatroute that uses a query string number:Example:
/repeat?word=Wow×=3should show: Wow Wow WowHint:
request.args.get('times', 1)returns a string; convert to int safely. - Modify
/messageto also show how many characters your message has. - Make a new route
/math/addthat adds two numbers from the query string:Example:
/math/add?a=2&b=5should show: 7Keep it simple and handle missing inputs kindly.
Stretch Idea (Optional)
Create a route that returns a tiny JSON message:
Add this to app.py:
from flask import jsonify
@app.route('/api/echo')
def api_echo():
word = request.args.get('word', 'hello')
return jsonify({"you_said": word})Then test: http://127.0.0.1:5000/api/echo?word=hi
Real-World Connection
- Online stores use routes to show products (/products/42).
- Search boxes use query strings (/search?term=shoes).
- Contact forms use POST to send messages securely to the server.
Summary
- Routes connect URLs to Python functions.
- GET is for reading; POST is for sending new data (like forms).
- You can read values from the URL using route parameters and query strings.
- Flask makes building routes simple and fun.
Homework (Short and Fun)
Write a new Flask app with at least three routes:
- A home page with links to the others
- A route with a route parameter (like /color/<name>)
- A route that reads a query string (like /favorite?thing=music)
Add one POST form that thanks the user for their input.
Extra Tips
- Keep route names short and clear.
- Return friendly messages when something is missing.
- Test in your browser after each small change.
Wrap-Up
You did it! You now understand routes and HTTP methods, and you've built a working mini web app with Python and Flask.