HTTP Methods and Routing

Loading concept...

Flask HTTP Methods and Routing: Your Web Traffic Control Center

The Big Picture: A Restaurant Analogy

Imagine a restaurant. Customers come in wanting different things:

  • Some want to see the menu (GET)
  • Some want to place an order (POST)
  • Some want to change their order (PUT)
  • Some want to cancel their order (DELETE)

Flask routing is like being the restaurant manager who directs each customer to the right waiter (view function) based on what they want!


What is an HTTP Method?

HTTP methods are the way your browser talks to a website. Think of them as different types of requests:

Method Purpose Restaurant Example
GET Read/View data “Show me the menu”
POST Create new data “I want to order pizza”
PUT Update existing data “Change my pizza to large”
DELETE Remove data “Cancel my order”

GET Method: “Show Me!”

GET is the most common method. When you type a website URL and press Enter, you’re making a GET request.

Simple Example

from flask import Flask
app = Flask(__name__)

@app.route('/menu')
def show_menu():
    return "Pizza, Burger, Salad"

What happens:

  1. User visits yoursite.com/menu
  2. Flask sees the /menu path
  3. Flask calls show_menu() function
  4. User sees “Pizza, Burger, Salad”

With URL Parameters

@app.route('/item/<food_name>')
def show_item(food_name):
    return f"You asked about: {food_name}"

Visit /item/pizza → See “You asked about: pizza”


POST Method: “Create Something New!”

POST sends data TO the server. Like filling out a form and clicking Submit.

Example: Taking an Order

from flask import Flask, request

@app.route('/order', methods=['POST'])
def place_order():
    food = request.form.get('food')
    return f"Order received: {food}"

Key Points:

  • We add methods=['POST'] to allow POST
  • request.form.get() reads the data sent
  • By default, routes only accept GET

Quick Diagram

graph TD A[User fills form] --> B[Clicks Submit] B --> C[POST request sent] C --> D[Flask receives data] D --> E[Returns confirmation]

PUT Method: “Update This!”

PUT changes existing data. Like editing your profile.

Example: Updating an Order

@app.route('/order/<int:order_id>',
           methods=['PUT'])
def update_order(order_id):
    new_food = request.form.get('food')
    return f"Order {order_id} changed to {new_food}"

Notice: We use <int:order_id> to capture the order number!


DELETE Method: “Remove This!”

DELETE removes data from the server.

Example: Canceling an Order

@app.route('/order/<int:order_id>',
           methods=['DELETE'])
def cancel_order(order_id):
    return f"Order {order_id} canceled"

Real Use: APIs for apps, admin panels, user account deletion.


View Functions: The Workers

A view function is the Python function that runs when someone visits a URL. Think of it as the waiter who does the actual work.

Anatomy of a View Function

@app.route('/hello')     # The decorator
def say_hello():         # The function
    # Do some work here
    return "Hello!"      # The response

Rules:

  1. Must have @app.route() decorator above it
  2. Must return something (string, HTML, JSON)
  3. Can accept parameters from the URL

View Functions Can Return Many Things

# Return plain text
@app.route('/text')
def text_view():
    return "Just text"

# Return HTML
@app.route('/html')
def html_view():
    return "<h1>Big Title</h1>"

# Return JSON (for APIs)
@app.route('/json')
def json_view():
    return {"name": "Pizza", "price": 10}

Endpoint Naming: Giving Routes a Nickname

An endpoint is the internal name Flask uses to identify a route. By default, it’s the function name.

Default Endpoint

@app.route('/menu')
def show_menu():      # Endpoint = "show_menu"
    return "Menu here"

Custom Endpoint

@app.route('/menu', endpoint='menu_page')
def show_menu():      # Endpoint = "menu_page"
    return "Menu here"

Why Use Endpoints?

from flask import url_for

# Generate URL from endpoint name
link = url_for('menu_page')  # Returns "/menu"

Benefit: If you change the URL, your code still works!


Multiple Routes, Same Function

One function can handle multiple URLs. Super useful!

Example: Home Page

@app.route('/')
@app.route('/home')
@app.route('/index')
def home_page():
    return "Welcome Home!"

All three URLs show the same page:

  • yoursite.com/
  • yoursite.com/home
  • yoursite.com/index

Example: With Default Values

@app.route('/greet/')
@app.route('/greet/<name>')
def greet(name='Guest'):
    return f"Hello, {name}!"
  • /greet/ → “Hello, Guest!”
  • /greet/Alice → “Hello, Alice!”

Request Dispatching: How Flask Finds Your Route

When a request arrives, Flask follows these steps:

graph TD A[Request arrives] --> B[Extract URL path] B --> C[Check all routes] C --> D{Match found?} D -->|Yes| E[Call view function] D -->|No| F[Return 404 Error] E --> G[Return response]

The Matching Process

  1. URL Extraction: Flask gets the path (like /menu)
  2. Route Matching: Compares with all @app.route() patterns
  3. Method Check: Verifies the HTTP method is allowed
  4. Parameter Parsing: Extracts any URL variables
  5. Function Call: Runs the matched view function
  6. Response: Sends result back to browser

See All Your Routes

# Print all registered routes
print(app.url_map)

Output shows every route, method, and endpoint!


Putting It All Together

Here’s a mini restaurant API using everything we learned:

from flask import Flask, request

app = Flask(__name__)

# GET - View menu
@app.route('/')
@app.route('/menu')
def show_menu():
    return {"items": ["Pizza", "Burger"]}

# POST - Place order
@app.route('/order', methods=['POST'])
def create_order():
    item = request.json.get('item')
    return {"status": "ordered", "item": item}

# PUT - Update order
@app.route('/order/<int:id>', methods=['PUT'])
def update_order(id):
    new_item = request.json.get('item')
    return {"status": "updated", "id": id}

# DELETE - Cancel order
@app.route('/order/<int:id>', methods=['DELETE'])
def delete_order(id):
    return {"status": "canceled", "id": id}

if __name__ == '__main__':
    app.run(debug=True)

Key Takeaways

Concept Remember This
GET Read data, default method
POST Create new data
PUT Update existing data
DELETE Remove data
View Function The function that handles requests
Endpoint Internal name for a route
Multiple Routes Stack decorators for aliases
Dispatching Flask matches URL → finds function → runs it

You Did It!

You now understand how Flask routes work! Think of yourself as the restaurant manager who knows exactly which waiter handles which customer request.

Next Step: Build your own mini API with these methods!

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.