Skip to content

Flask routes and variable rules

In Flask, routes are used to map specific URLs to Python functions, allowing the application to handle different HTTP requests for various endpoints.^[400-devops-09-scripting-language-python-introduction-part-4http-readme.md]

Defining Routes

Routes are defined using the @app.route decorator. By default, a basic route might map the root URL (/) to a function that returns a response, such as "Hello, World!".^[400-devops-09-scripting-language-python-introduction-part-4http-readme.md]

@app.route("/")
def hello_world():
    return "<p>Hello, World!</p>"

Variable Rules

Variable rules allow a URL to accept dynamic parameters. By defining a route with variable sections, you can pass values from the URL directly to your function arguments.^[400-devops-09-scripting-language-python-introduction-part-4http-readme.md]

For example, a route like /get/<customerID> can be defined to retrieve a specific item based on the provided ID. The variable part of the route is placed within angle brackets <> in the decorator definition.^[400-devops-09-scripting-language-python-introduction-part-4http-readme.md]

@app.route("/get/<string:customerID>", methods=['GET'])
def get_customer(customerID):
    # Logic to retrieve customer
    return customer

HTTP methods

Routes can be restricted to specific HTTP methods, such as GET or POST, using the methods argument in the decorator.^[400-devops-09-scripting-language-python-introduction-part-4http-readme.md]

  • GET: Typically used for retrieving data.^[400-devops-09-scripting-language-python-introduction-part-4http-readme.md]
  • POST: Typically used for sending data to the server.^[400-devops-09-scripting-language-python-introduction-part-4http-readme.md]

If a route is configured to accept only POST requests but is accessed via a browser (which defaults to GET), the server will return a Method Not Allowed error.^[400-devops-09-scripting-language-python-introduction-part-4http-readme.md]

Sources

^[400-devops-09-scripting-language-python-introduction-part-4http-readme.md]