16

I defined some resource called WorkerAPI using flask-restful and the plan is to process POST request from /api/workers/new and GET request from /api/workers/. When using the following code

api.add_resource(WorkerAPI, '/api/workers/new')
api.add_resource(WorkerAPI, '/api/workers/')

I get errors:

AssertionError: View function mapping is overwriting an existing endpoint function: workerapi

Then I tried to use the following, which seems to work, although I don't know why it works.

api.add_resource(WorkerAPI, '/api/workers/new', endpoint='/workers/new')
api.add_resource(WorkerAPI, '/api/workers/', endpoint='/workers/')

It looks like redundant information to me though. It seems the site works as long as the two endpoints are defined as different strings. What does endpoint mean here?

nos
  • 19,875
  • 27
  • 98
  • 134

2 Answers2

12

The thing is that the add_resource function registers the routes with the framework using the given endpoint. If an endpoint isn't given then Flask-RESTful generates one for you from the class name.

Your case is WorkerAPI, the endpoint will beworkerapi for these two methods, better make endpoint explicit and avoid to have conflicting endpoint names registered.

For what's endpoint, you can refer to this answer for more details.

Tiny.D
  • 6,466
  • 2
  • 15
  • 20
1

'endpoint' is actually an identifier that is used in determining what logical unit of your code should handle a specific request.

So, an URL path is mapped to an endpoint and then an endpoint is mapped to a view function in your flask app.

In your case, when you are explicitly defining your endpoints for your resources, it helps the flask app internally to map it efficiently to a list of routes, while when your are not explicitly defining it, flask takes some default value, as explained by @Tiny.D, in the above answer.

hansrajswapnil
  • 549
  • 1
  • 6
  • 14