Build your first Python web API using Flask - the tiny but mighty web framework! (Ages 8-18)
Session Date: Saturday, May 2, 2026 at 11:00 AM EST
| ๐ง Grades 3-5 | ๐ง Grades 6-8 | ๐ Grades 9-12 | |
|---|---|---|---|
| ๐ Python | Understand Python basics | Write functions and use dictionaries | Use classes and list comprehensions |
| ๐ถ๏ธ Flask | Run a Flask app, visit routes | Create routes with parameters | Build JSON APIs with validation |
| ๐ Compare | See C# vs Python side-by-side | Explain key differences | Analyze trade-offs of each |
| ๐ By End | Run Flask app and see output | Create 3+ API endpoints | Build complete CRUD API |
๐ฌ Setup: Students act out a restaurant experience
๐ฝ๏ธ THE RESTAURANT IS LIKE A WEB SERVER! ๐
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ
โ ๐ค CUSTOMER ๐งโ๐ณ CHEF ๐ MENU โ
โ (Browser) (Flask) (Routes) โ
โ โ
โ "I'd like the "Coming right /pizza ๐ โ
โ pizza please!" up!" /burger ๐ โ
โ /salad ๐ฅ โ
โ โ โ โ
โ โผ โผ โ
โ โโโโโโโโโโโ โโโโโโโโโโโ โ
โ โ REQUEST โโโโโโโโโถโ PROCESS โ โ
โ โ /pizza โ โ make โ โ
โ โโโโโโโโโโโ โ pizza โ โ
โ โโโโโโฌโโโโโ โ
โ โโโโโโโโโโโ โ โ
โ โRESPONSE โโโโโโโโโ โ
โ โ ๐ โ โ
โ โโโโโโโโโโโ โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
๐ฌ Discussion:
"When you go to a restaurant, you ask for something from the menu (REQUEST), the chef makes it (PROCESS), and brings it back (RESPONSE). Web servers work the same way!"
๐ Look at these two code snippets - what's different?
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ C# (ASP.NET Core) ๐ท โ
โ โ
โ [HttpGet] โ
โ public ActionResult<List<Book>> GetAllBooks() โ
โ { โ
โ return Ok(_books); โ
โ } โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Python (Flask) ๐ โ
โ โ
โ @app.route('/books') โ
โ def get_all_books(): โ
โ return jsonify(books) โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
๐ฏ Differences to spot:
- ๐ท C# uses
{}braces, ๐ Python uses indentation - ๐ท C# has type declarations, ๐ Python doesn't
- ๐ท C# uses
[HttpGet], ๐ Python uses@app.route() - ๐ Python is often shorter and simpler!
WHY IS IT CALLED FLASK? ๐งช
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ
โ ๐งช โ
โ / \ Flask is named after a โ
โ / \ LABORATORY FLASK! โ
โ / \ โ
โ | | It's a "micro" framework - โ
โ | | small and simple, like a โ
โ |________| tiny flask in a science lab. โ
โ โ
โ The pepper emoji ๐ถ๏ธ is because "Flask" โ
โ sounds like "Flasche" (bottle) in German! โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
HOW FLASK HANDLES A REQUEST ๐
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ
โ 1๏ธโฃ BROWSER 2๏ธโฃ FLASK APP โ
โ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ โ HTTP GET โ โ โ
โ โ Chrome ๐ โโโโโโโโโโโโโโโโถโ @app.route('/books') โ โ
โ โ โ /api/books โ def get_all_books(): โ โ
โ โ โ โ return jsonify(books) โ โ
โ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโ โ
โ โฒ โ โ
โ โ โผ โ
โ โ 3๏ธโฃ PYTHON RUNS THE FUNCTION โ
โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ HTTP 200 OK โ books = [ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโ {"title": "Harry Potter"}โ โ
โ โ + JSON data โ ] โ โ
โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ
โ 4๏ธโฃ BROWSER DISPLAYS THE DATA โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ [{"id": 1, "title": "Harry Potter", "author": "J.K... โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
SIDE-BY-SIDE COMPARISON ๐ท vs ๐
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ASP.NET Core (C#) ๐ท โ Flask (Python) ๐ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ โ
โ Statically typed โ Dynamically typed โ
โ (must declare types) โ (types are automatic) โ
โ โ โ
โ string name = "Sam"; โ name = "Sam" โ
โ โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ โ
โ Uses Controllers โ Uses route decorators โ
โ โ โ
โ [HttpGet] โ @app.route('/books') โ
โ public ActionResult Get() โ def get_books(): โ
โ { return Ok(data); } โ return jsonify(data) โ
โ โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ โ
โ Curly braces { } โ Indentation (spaces) โ
โ Semicolons ; โ No semicolons! โ
โ โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ โ
โ dotnet run โ flask run โ
โ or python -m flask run or python app.py โ
โ โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
BOTH CAN:
โ
Create REST APIs
โ
Handle GET, POST, PUT, DELETE
โ
Return JSON
โ
Render HTML templates
โ
Connect to databases
Session20/
โโโ README.md โ ๐ You are here!
โโโ app.py โ ๐ Our Flask application
โโโ requirements.txt โ ๐ฆ Python packages we need
โโโ .gitignore โ ๐ Files Git should ignore
โโโ templates/
โโโ index.html โ ๐จ HTML template for the homepage
- โ Completed Session 19 (Python Basics)
- โ Python 3.8+ installed
- โ VS Code or PyCharm installed
- โ Understanding of HTTP from Sessions 11-13
๐ Create a new folder and open it:
# Create folder
mkdir flask-library
cd flask-library
# Create a virtual environment (keeps packages organized)
python -m venv venv
# Activate it!
# On Mac/Linux:
source venv/bin/activate
# On Windows:
venv\Scripts\activate
# You'll see (venv) in your terminal - that means it's working! โ
๐จ What's a virtual environment?
VIRTUAL ENVIRONMENT = YOUR OWN PYTHON SANDBOX ๐๏ธ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ
โ Without venv: With venv: โ
โ โ
โ ๐ System Python ๐ฆ Project Python โ
โ All packages mixed Only YOUR packages โ
โ Might break things! Safe and organized! โ
โ โ
โ Think of it like having your own locker at school - โ
โ your stuff stays separate from everyone else's! ๐ โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
๐ฆ Install Flask using pip:
pip install flask๐ Create requirements.txt:
Flask==3.0.0
๐ก Why requirements.txt?
It's like a shopping list for your project! Anyone can run
pip install -r requirements.txtto get all the same packages you're using.
๐ Create file: app.py
# ====================================
# ๐ถ๏ธ Flask Library API
# Our first Python web application!
# ====================================
from flask import Flask, jsonify, request, render_template
# Create our Flask app ๐
app = Flask(__name__)
# ====================================
# ๐ Our Book Data (in-memory storage)
# Just like our C# List<Book>!
# ====================================
books = [
{"id": 1, "title": "Harry Potter", "author": "J.K. Rowling", "pages": 309, "available": True},
{"id": 2, "title": "The Hobbit", "author": "J.R.R. Tolkien", "pages": 310, "available": True},
{"id": 3, "title": "Diary of a Wimpy Kid", "author": "Jeff Kinney", "pages": 217, "available": False}
]
# ====================================
# ๐ HOME ROUTE - Returns HTML page
# ====================================
@app.route('/')
def home():
"""
This is like our home page!
render_template loads the HTML file from /templates folder
"""
return render_template('index.html', book_count=len(books))
# ====================================
# ๐ GET ALL BOOKS
# Same as our C# GetAllBooks()!
# ====================================
@app.route('/api/books', methods=['GET'])
def get_all_books():
"""
Returns all books as JSON
C# equivalent:
[HttpGet]
public ActionResult<List<Book>> GetAllBooks()
{
return Ok(_books);
}
"""
return jsonify(books)
# ====================================
# ๐ GET ONE BOOK BY ID
# Same as our C# GetBook(int id)!
# ====================================
@app.route('/api/books/<int:book_id>', methods=['GET'])
def get_book(book_id):
"""
Returns a single book by ID
<int:book_id> is like {id} in C# routes
C# equivalent:
[HttpGet("{id}")]
public ActionResult<Book> GetBook(int id)
"""
# Find the book with matching ID
book = next((b for b in books if b['id'] == book_id), None)
if book is None:
return jsonify({"error": f"Book with ID {book_id} not found"}), 404
return jsonify(book)
# ====================================
# โ CREATE A NEW BOOK
# Same as our C# CreateBook()!
# ====================================
@app.route('/api/books', methods=['POST'])
def create_book():
"""
Creates a new book from JSON data
C# equivalent:
[HttpPost]
public ActionResult<Book> CreateBook(Book newBook)
"""
# Get JSON data from request
data = request.get_json()
# Validate required fields
if not data or 'title' not in data or 'author' not in data:
return jsonify({"error": "Title and author are required!"}), 400
# Create new book with auto-generated ID
new_book = {
"id": max(b['id'] for b in books) + 1 if books else 1,
"title": data['title'],
"author": data['author'],
"pages": data.get('pages', 0), # Default to 0 if not provided
"available": True
}
books.append(new_book)
# Return 201 Created with the new book
return jsonify(new_book), 201
# ====================================
# ๐ค CHECKOUT A BOOK
# ====================================
@app.route('/api/books/<int:book_id>/checkout', methods=['POST'])
def checkout_book(book_id):
"""Checkout a book - mark it as unavailable"""
book = next((b for b in books if b['id'] == book_id), None)
if book is None:
return jsonify({"error": f"Book with ID {book_id} not found"}), 404
if not book['available']:
return jsonify({"error": f"'{book['title']}' is already checked out!"}), 400
book['available'] = False
return jsonify({"message": f"Successfully checked out '{book['title']}'! ๐"})
# ====================================
# ๐ฅ RETURN A BOOK
# ====================================
@app.route('/api/books/<int:book_id>/return', methods=['POST'])
def return_book(book_id):
"""Return a book - mark it as available"""
book = next((b for b in books if b['id'] == book_id), None)
if book is None:
return jsonify({"error": f"Book with ID {book_id} not found"}), 404
if book['available']:
return jsonify({"error": f"'{book['title']}' wasn't checked out!"}), 400
book['available'] = True
return jsonify({"message": f"Thank you for returning '{book['title']}'! ๐"})
# ====================================
# ๐ RUN THE APP
# ====================================
if __name__ == '__main__':
# debug=True means it auto-reloads when you save! ๐
print("๐ถ๏ธ Starting Flask Library API...")
print("๐ Visit http://localhost:5000 in your browser!")
app.run(debug=True, port=5000)๐ Create folder: templates/
๐ Create file: templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>๐ถ๏ธ Flask Library API</title>
<style>
/* Fun, kid-friendly styling! */
body {
font-family: 'Comic Sans MS', 'Segoe UI', sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
color: white;
}
.container {
background: rgba(255, 255, 255, 0.95);
border-radius: 20px;
padding: 30px;
color: #333;
box-shadow: 0 10px 40px rgba(0,0,0,0.3);
}
h1 {
color: #667eea;
text-align: center;
}
.emoji-big {
font-size: 4rem;
text-align: center;
display: block;
}
.endpoint {
background: #f8f9fa;
border-left: 4px solid #667eea;
padding: 15px;
margin: 10px 0;
border-radius: 0 10px 10px 0;
}
.method {
display: inline-block;
padding: 3px 10px;
border-radius: 5px;
font-weight: bold;
margin-right: 10px;
}
.get { background: #28a745; color: white; }
.post { background: #ffc107; color: black; }
code {
background: #e9ecef;
padding: 2px 6px;
border-radius: 4px;
font-family: monospace;
}
.book-count {
font-size: 2rem;
text-align: center;
color: #667eea;
}
</style>
</head>
<body>
<div class="container">
<span class="emoji-big">๐ถ๏ธ๐๐</span>
<h1>Flask Library API</h1>
<p class="book-count">๐ {{ book_count }} books in the library!</p>
<h2>๐ฏ API Endpoints</h2>
<div class="endpoint">
<span class="method get">GET</span>
<code>/api/books</code>
<p>Get all books in the library</p>
</div>
<div class="endpoint">
<span class="method get">GET</span>
<code>/api/books/<id></code>
<p>Get a specific book by ID</p>
</div>
<div class="endpoint">
<span class="method post">POST</span>
<code>/api/books</code>
<p>Add a new book (send JSON with title, author, pages)</p>
</div>
<div class="endpoint">
<span class="method post">POST</span>
<code>/api/books/<id>/checkout</code>
<p>Check out a book</p>
</div>
<div class="endpoint">
<span class="method post">POST</span>
<code>/api/books/<id>/return</code>
<p>Return a book</p>
</div>
<h2>๐งช Try It!</h2>
<p>Open your browser to: <code>http://localhost:5000/api/books</code></p>
<p>Or use Postman/curl to test the POST endpoints!</p>
<hr>
<p style="text-align: center; color: #666;">
Built with โค๏ธ at CoderDojo | Session 20
</p>
</div>
</body>
</html># Make sure you're in your project folder with venv activated
python app.py๐ You should see:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ๐ถ๏ธ Starting Flask Library API... โ
โ ๐ Visit http://localhost:5000 in your browser! โ
โ * Running on http://127.0.0.1:5000 โ
โ * Debug mode: on โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
๐ Open your browser and visit:
http://localhost:5000- See the homepage!http://localhost:5000/api/books- See all books as JSON!http://localhost:5000/api/books/1- See just Harry Potter!
๐งช Test GET all books:
curl http://localhost:5000/api/books๐งช Test POST new book:
curl -X POST http://localhost:5000/api/books \
-H "Content-Type: application/json" \
-d '{"title": "Percy Jackson", "author": "Rick Riordan", "pages": 375}'๐งช Test checkout:
curl -X POST http://localhost:5000/api/books/1/checkout GETTING A BOOK BY ID - C# vs Python ๐ท๐
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ C# (ASP.NET Core) - 12 lines ๐ท โ
โ โ
โ [HttpGet("{id}")] โ
โ public ActionResult<Book> GetBook(int id) โ
โ { โ
โ var book = _books.FirstOrDefault(b => b.Id == id); โ
โ โ
โ if (book == null) โ
โ { โ
โ return NotFound($"Book {id} not found"); โ
โ } โ
โ โ
โ return Ok(book); โ
โ } โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Python (Flask) - 8 lines ๐ โ
โ โ
โ @app.route('/api/books/<int:book_id>') โ
โ def get_book(book_id): โ
โ book = next((b for b in books โ
โ if b['id'] == book_id), None) โ
โ โ
โ if book is None: โ
โ return jsonify({"error": "Not found"}), 404 โ
โ โ
โ return jsonify(book) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Both do the SAME thing! Python is just more concise. ๐
๐ Circle Share - Answer one:
- "One thing I like about Flask compared to ASP.NET Core is..."
- "Python feels different from C# because..."
- "The hardest part about learning a new framework is..."
- "I want to build ___ with Flask..."
- ๐ถ๏ธ Flask app starts without errors
- ๐ Homepage loads at localhost:5000
- ๐ GET /api/books returns all books
- ๐ GET /api/books/1 returns Harry Potter
- โ GET /api/books/999 returns 404 error
- โ POST /api/books creates a new book
- ๐ค Checkout endpoint works
- ๐ฅ Return endpoint works
- ๐จ Template displays book count correctly
Add a route that searches for books by title:
@app.route('/api/books/search/<title>')
def search_books(title):
# Find books where title contains the search term
passAdd routes to update and delete books:
PUT /api/books/<id>- Update a bookDELETE /api/books/<id>- Delete a book
Use your JavaScript knowledge from Sessions 16-18 to create a frontend that calls your Flask API!
Replace the in-memory list with SQLite:
from flask_sqlalchemy import SQLAlchemy| Term | ๐ Kid-Friendly Definition | ๐ป Example |
|---|---|---|
| ๐ถ๏ธ Flask | A small Python web framework | from flask import Flask |
| ๐ฏ Route | A URL path that triggers a function | @app.route('/books') |
| ๐ท๏ธ Decorator | Special @ symbol that adds features |
@app.route() |
| ๐ฆ jsonify | Converts Python data to JSON | return jsonify(books) |
| ๐ Template | HTML file that Flask can fill in | render_template('index.html') |
| ๐งช Virtual Environment | Isolated Python package space | python -m venv venv |
๐จโ๐ฉโ๐ง Talk to a family member:
"Today I learned Flask, a Python web framework! It's like ASP.NET Core that we learned in C#, but with Python. Python uses less code to do the same things - it's like texting in shorthand instead of writing full sentences!"
๐ Real-world examples of Flask:
- ๐ต Netflix uses Flask for some services
- ๐ฑ Uber started with Flask
- ๐ LinkedIn uses Flask for some features
- ๐ค Many AI/ML projects use Flask for APIs
๐ Mini-Project Idea: Build a "Movie Rating" API with Flask:
- Store movies with titles and ratings
- Add routes to list, add, and rate movies
- Create a simple frontend to display them
WHAT WE LEARNED TODAY ๐ง
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ
โ 1. ๐ Flask is Python's lightweight web framework โ
โ โ
โ 2. ๐ฏ Routes map URLs to Python functions โ
โ โ
โ 3. ๐ฆ jsonify() converts Python dicts to JSON โ
โ โ
โ 4. ๐ Flask and ASP.NET Core do similar things โ
โ but Flask uses less code โ
โ โ
โ 5. ๐งช Virtual environments keep packages organized โ
โ โ
โ 6. ๐ Templates let us return HTML pages โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
COMING UP IN SESSION 21: FINAL SHOWCASE! ๐ญ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ
โ ๐ Present your complete project! โ
โ โ
โ You've learned: โ
โ โโโ C# fundamentals (Sessions 1-4) โ
โ โโโ Object-Oriented Programming (Sessions 5-10) โ
โ โโโ ASP.NET Core Web APIs (Sessions 11-15) โ
โ โโโ Frontend (HTML/CSS/JS) (Sessions 16-18) โ
โ โโโ Python & Flask (Sessions 19-20) โ
โ โ
โ Time to show off what you've built! ๐ โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
You're almost at the finish line! Keep coding! ๐๐๐ถ๏ธ