Search code examples
pythonrestflaskflask-restful

`fields.Url('some_resource')` doesn't append the `id` at the end if using blueprints


I am using blueprints and I have this line to create the blueprint:

api_bp = Blueprint('api', __name__)

And some_resources is added and blueprint is registered by below lines:

rest_api = Api()
rest_api.init_app(api_bp)
rest_api.add_resource(SomeResourceApi, '/some_resources', '/some_resources/<int:some_resource_id>', endpoint='some_resources')
app.register_blueprint(api_bp, url_prefix='/some/api/v1.0')

The fields dict used for marshal() has 'uri': fields.Url('api.some_resources'), The output that I receive is "uri": "/some/api/v1.0/some_resources" inside my response. Notice that the id is not appended at the end in the url.

Just to be sure I replaced the line 'uri': fields.Url('api.some_resources'), inside my field dict to 'id': fields.Integer and in this case the integer id is returned correctly inside the response.

Also I have tested both with the decorator @marshal_with and the method marshal(), that doesn't make any difference.

For now, I am getting my work done by having my fields dict to have an extra field: id with the value fields.Integer which contains the actual id, so the output has these two fields in response which collectively gives the complete address:

"uri": "/some/api/v1.0/some_resources",
"id": 11

While this serves the purpose, it looks kind of hacky.

Am I doing anything wrong that the ids are not appended in the response when using fields.Url()?

Library Version details:

Flask==1.0.2

Flask-RESTful==0.3.6

Flask-SQLAlchemy==2.3.2

SQLAlchemy==1.2.10

Corresponding github issue: https://github.com/flask-restful/flask-restful/issues/774


Solution

  • I don't think you should route the request for a list of items (/some_resources) and the detail for single items (/some_resources/:id) through the same resource class.

    fields.Url is just calling flask's url_for() under the hood and is probably just using the first matching resource path that it finds. Maybe if you swapped the order of the paths passed to add_resource it would work.