Reputation: 2095
I currently work on a flask API and think I have a misconception how to implement my endpoints. Currently I handle my requests like this: I have an endpoint and then handle the data passed by the request.
@api.route("/deleteitem")
class DeleteItem(Resource):
def delete(self):
item = request.get_json()["item"]
items = [x.get("item") for x in store]
if item in items:
index = items.index(item)
store.pop(index)
return {"message": "item deleted"}, 200
return {"message": "item not found"}, 404
In almost every tutorial this is handled differently: Instead of getting the data passed in the request body, it is directly done via the endpoint like this:
@api.route("/deleteitem/<string:item>")
class DeleteItem(Resource):
def delete(self, item):
items = [x.get("item") for x in store]
if item in items:
index = items.index(item)
store.pop(index)
return {"message": "item deleted"}, 200
return {"message": "item not found"}, 404
My question is: Am I doing it wrong or is that just a style issue? Both seems to work, but to be honest, my APIs are quite simple, but I don´t want to embed bad coding style. What is preferable and why?
Upvotes: 0
Views: 379
Reputation: 1790
I don't think your initial attempt is wrong perse, but the second one is preferred. This probably has to do with implicit vs. explicit. In the second example it's clear you will delete 1 item and from the url you can already tell which one. If this is "hidden" in the body it could be multiple items. The same logic would apply for the GET requests as well. are we retrieving 1 or more items? This is also why plurals are often recommended (so not /item but rather /items), which you can then narrow down.
It seems most examples seem to agree on this, including the article in this link as well as this one.
Upvotes: 1