Labs ICT
โญ Pro Login

HTTP Methods

Handling GET, POST, PUT, DELETE.

HTTP Methods

By default, a Flask route only responds to GET requests. But real applications need more than that. You specify allowed methods using the methods parameter:

@app.route("/submit", methods=["GET", "POST"])
def submit():
    if request.method == "POST":
        return "Form submitted!"
    return "Show the form"

Each HTTP method has a purpose. GET retrieves data โ€” it should never change anything on the server. POST sends data to create a new resource, like submitting a form or creating a user account. PUT replaces an existing resource entirely, while DELETE removes one.

To access the data a user sends, Flask provides the request object. For form submissions (POST), use request.form:

from flask import request

@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "POST":
        username = request.form["username"]
        password = request.form["password"]
        # validate credentials...
        return f"Welcome, {username}!"
    return "Login form"

For query parameters โ€” those key-value pairs after the ? in a URL โ€” use request.args:

@app.route("/search")
def search():
    query = request.args.get("q", "")
    page = request.args.get("page", 1, type=int)
    return f"Searching for '{query}' on page {page}"

A URL like /search?q=flask&page=2 would extract q as "flask" and page as 2.

PUT and DELETE work similarly โ€” the data comes through request.form or request.get_json() depending on the content type. For REST APIs, JSON is more common:

@app.route("/api/item/", methods=["PUT"])
def update_item(item_id):
    data = request.get_json()
    return {"updated": item_id, "data": data}

๐Ÿงช Quick Quiz

How do you get form data in Flask?