pythonflaskendpointprefixblueprint

Add prefix to all URLs while using Blueprint


I am trying to prefix all endpoints with /api/, but I am getting 404 in return if not providing directly in the URL or while registering blueprint.

main.py

from init import app

from modules.User import User

app.register_blueprint(User)

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

init.py

from flask import Flask

# initiating application instance
app = Flask(__name__)

# app configurations
app.config["SCRIPT_NAME"] = "/api/"

# -- OR --

app.config["APPLICATION_ROOT"] = "/api/"
...

modules/User.py

from flask import request, Blueprint

User = Blueprint("user_blueprint", __name__)

# if "/api/" is provided directly 
@User.route("/api/", methods=["GET"]) 
def get():
    return "Called get method"


# 404 if "/" is provided
@User.route("/", methods=["GET"]) 
def get():
    return "Called get method"

Solution

  • APPLICATION_ROOT and SCRIPT_NAME define the base path where the application is mounted by the WSGI server.

    They don’t automatically add /api to your routes during development, so your @User.route("/") ends up at /, not /api/, hence you get the 404.

    You can achieve the desired behavior in one of the following ways: