HTTP Methods (GET vs POST)
HTTP methods tell the server what the client intends to do.
flowchart TD
A["request arrives"] --> B{"does the rule allow this method?"}
B -->|no| C["405 Method Not Allowed -- view not called"]
B -->|yes| D{"request.method"}
D -->|GET| E["render the form -- no side effects"]
D -->|POST| F["read request.form, validate"]
F --> G{"valid?"}
G -->|no| H["re-render with errors"]
G -->|yes| I["do the work, then redirect"]
E --> J["safe to reload, bookmark, prefetch"]
I --> K["never answer a POST with HTML directly"]
Use GET for reading:
- fetching a page
- querying data
Characteristics:
- should be safe (no state change)
- parameters usually appear in the URL (
?q=...) - can be cached
Use POST for writing/changing state:
- submitting forms
- creating a new resource
- login/register actions
Characteristics:
- carries data in request body
- not cached by default
- can trigger CSRF protections (later)
Allowing methods in Flask routes
Section titled “Allowing methods in Flask routes”By default, @app.route allows GET.
To accept POST:
from flask import Flask, request
app = Flask(__name__)
@app.route("/submit", methods=["GET", "POST"])
def submit():
if request.method == "POST":
return "Received POST", 201
return "Submit page"A practical mental model
Section titled “A practical mental model”- GET: “Give me the current representation of this resource.”
- POST: “Process this data.”
Common beginner mistakes
Section titled “Common beginner mistakes”- Using GET for actions like
/delete?id=5(dangerous) - Forgetting to restrict methods → 405 Method Not Allowed in production
- Not validating/escaping user input
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Create a Flask App
Section titled “Exercise 1 – Create a Flask App”Exercise 2 – Dynamic Route
Section titled “Exercise 2 – Dynamic Route”Exercise 3 – Return JSON
Section titled “Exercise 3 – Return JSON”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading