Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question: optional/wildcard url parameter #956

Open
bastianb opened this issue Nov 2, 2022 · 1 comment
Open

Question: optional/wildcard url parameter #956

bastianb opened this issue Nov 2, 2022 · 1 comment

Comments

@bastianb
Copy link

bastianb commented Nov 2, 2022

Hi,
I would like to have a route with a param in it but not having to have to specify it in the method level, like:

Class ComponentList(Resource):
    def get(self):  # note that there is no some_random_string param here
        ...
api.add_resource(ComponentList, '/api/<some_random_string>/components')

For the moment I couldn't find any keyword in the code, * doesn't work either. Is it possible?

@HomiGrotas
Copy link

HomiGrotas commented Feb 7, 2023

Hi @bastianb , fortunately there isn't an option to do so.
I would suggest to create a middleware that catches this endpoint and then returns your resource response:


from flask_restful import Api, Resource 
from flask import Flask, request


app = Flask(__name__)
api = Api(app)


class ComponentList(Resource):
    def get(self):  # note that there is no some_random_string param here
        ...
        return "my_response"


@app.route('/api/<string:ignored>/components')
def middleware(ignored):
    method = request.method.lower()
    if hasattr(ComponentList, method):
        return getattr(ComponentList(), method)()


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

Notice that if you need a scaleable solution you can use a class decorator

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants