Search code examples
python-3.xparsingflaskflask-restfulurl-parsing

Flask: How to pass url as an input?


The requirement is to pass an url as an input to the endpoint.

The url may look like this:

"google.com:443/something/something.html?q=go+lang"

How can I pass it to my api get method as localhost:5001/api/google.com:443/something/something.html?q=go+lang

Currently, I am using Flask and Flask-restful even if I encoded the url to

google.com%3A443%2Fsomething%2Fsomething.html%3Fq%3Dgo%2Blang

and pass it to my api

api.add_resource(UrlInfo, '/api/<encoded_url>')

The system won't take it as a whole. It will decoded it and return 404

I would like to ask if there's a proper way that I can pass the url as a whole? the url may contains multiple level (slashes) in the path. How can I handle it?

Thanks


Solution

  • Try

    api.add_resource(UrlInfo, '/api/<path:encoded_url>')
    

    Reference: https://flask.palletsprojects.com/en/1.1.x/quickstart/#variable-rules


    Here's what I tried, definitely works:

    route('/testurl/<path:input_url>')
    def testurl(input_url):
        return input_url
    

    URL called: http://127.0.0.1:5000/codesubmission/testurl/http://www.google.com/testthisout/

    Output on page: http://www.google.com/testthisout/