melchoir55
melchoir55

Reputation: 7276

Passing url to flask api endpoint

I have a flask api which works quite well. Recently, we added a file upload section. Some server side code sends a call to the api, which in turn should trigger the processing of these uploaded files. The api call itself includes the absolute path to the file. So I have a route defined like:

@app.route('/Uploads/<string:userId>/<string:pathToFile>', methods=['POST'])

The code which is handling the upload is PHP. Before the path is sent to the api it is sent through a method which escapes the slashes, turning them into % signs. The method is called urlencode for those of you who are familiar with it.

The problem I'm having is that flask will not recognize the route. The request will fail even if it is as simple as:

localhost:5000/Uploads/testuser/%2Fhome

In the above example, I believe the % character is causing the problem. If I delete it, then the request succeeds.

I did find the following SO post which seems relevant: How to pass file path in a REST API ala Dropbox using Flask-RESTful? In it the FP suggests using the path placeholder instead of string. I tried doing that in my code like so:

 @app.route('/Uploads/<string:userId>/<path:pathToFile>', methods=['POST'])

I passed it a raw path (had not travelled through url encode). However, this didn't work.

Does anyone know the proper way to pass urls or paths via a flask api call?

Upvotes: 2

Views: 2338

Answers (1)

Jacob Budin
Jacob Budin

Reputation: 10003

You may be passing a forward slash (either / or %2F) as the first character. Don't do this, or else the endpoint as written won't be matched by Flask.

Have you tried a barebones example like so:

@app.route('/Uploads/<string:userId>/<path:pathToFile>')
def hello_world(userId, pathToFile):
    return '{uid} {path}'.format(uid=userId, path=pathToFile)

This does render the expected response.

Also: Review your function parameters to ensure they align with the URL parameters. Also check your request is POST and not GET, otherwise you'll get a Method Not Allowed error.

Upvotes: 2

Related Questions