HTTP Methods (GET vs POST)
HTTP methods tell the server what the client intends to do.
GET
Use GET for reading:
- fetching a page
- querying data
Characteristics:
- should be safe (no state change)
- parameters usually appear in the URL (
?q=...?q=...) - can be cached
POST
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
By default, @app.route@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"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
- GET: βGive me the current representation of this resource.β
- POST: βProcess this data.β
Common beginner mistakes
- Using GET for actions like
/delete?id=5/delete?id=5(dangerous) - Forgetting to restrict methods β 405 Method Not Allowed in production
- Not validating/escaping user input
π§ͺ Try It Yourself
Exercise 1 β Create a Flask App
Exercise 2 β Dynamic Route
Exercise 3 β Return JSON
If this helped you, consider buying me a coffee β
Buy me a coffeeWas this page helpful?
Let us know how we did
