[Python] Create Flask Restx endpoints without namespaces

Discussão em 'Python' iniciado por Stack, Setembro 1, 2025.

  1. Stack

    Stack Membro Participativo

    I'm working on the redesign of an API with Flask using Flask-restx, but I've a problem: We need a legacy version of the API that accepts the old URLs, for compatibility reasons, but I'm not understanding how to do this since Flask-restx requires a namespace to be declared.

    Urls should be something like this:

    {{host}}/api/v1/art/savegallery <- new one
    {{host}}/savegallery <- legacy


    In Flask I've something like this:

    app/__init__.py

    db = SQLAlchemy()
    migrate = Migrate()
    cors = CORS()


    def create_app(config_class=DevelopmentConfig):
    app = Flask(__name__)
    app.config.from_object(config_class)

    db.init_app(app=app)
    migrate.init_app(app=app, db=db)
    cors.init_app(app=app)

    from app.api import api_bp, legacy_bp
    app.register_blueprint(api_bp, url_prefix='/api/v1')
    app.register_blueprint(legacy_bp)

    return app


    /app/api/__init__.py

    api_bp = Blueprint('v1', __name__)
    legacy_bp = Blueprint('legacy', __name__)

    api_v1 = Api(
    app=api_bp,
    version='1.00',
    title='Art',
    description=(
    "API"
    ),
    )

    api_lgc = Api(
    app=legacy_bp,
    version='1.00',
    title='Art Legacy',
    description=(
    "API Legacy"
    ),
    )



    from app.art.routes import art_ns
    api_v1.add_namespace(art_ns)
    api_lgc.add_namespace(art_ns)


    app/art/routes.py

    art_ns = Namespace(name='art', description='Art Storage')
    #artlegacy_ns = Namespace(name='legacy', description='Art Storage')


    @art_ns.route('/savegallery')
    class GalleryAPI(Resource):
    def get(self):
    try:
    #data = request.json
    data = {}
    return {"foo":"bar"}, 200
    except Exception as e:
    print(e)
    return {"error": "Something happened"}, 500


    With this, I can access {{host}}/api/v1/art/savegallery correctly, but I'm not finding a way to declare the legacy one, since creating a URL this way would require at least the namespace part of the URL. Does Flask-restx have a way to declare those URLs and/or redirect the flow to the new ones?

    Continue reading...

Compartilhe esta Página