pythonflaskcrud

How does Flask use multiple methods in same route?


So, i'm writing a simple CRUD as it is in:

https://medium.com/@hillarywando/how-to-create-a-basic-crud-api-using-python-flask-cd68ef5fd7e3

and there you find these three methods:

@app.route("/request", methods=['POST']) def postRequest():

@app.route('/request', methods=['GET']) def getRequest():

@app.route("/request", methods=['PUT']) def putRequest():

While testing endpoints, something occourd me: in the example, GET, POST and PUT share the same route (/request), but when i enter "localhost:5000/request" on browser it only do the GET method.

I don't know if i made myself clear, but following the example above how does Flask or browser know which method to call, since there are three on the same route?

The same thing for GET and DELETE:

@app.route('/request/<id>', methods=['GET']) def getRequestId(id):

@app.route('/request/<id>', methods=['DELETE']) def deleteRequest(id):

How Flask or browser knows who to call? Or it is something that frontend should worry?

If it is frontend problem, how can i test all endpoints?

Thanks for the attencion

Tried to find the answer on google but didn't find anything


Solution

  • The client (whether a browser, or something else) has to specify the method in the HTTP request. A browser will usually default to GET, but may have an extension that lets you choose the method for the request.

    Other clients (curl, Postman, a library in a programming language, ...) will have ways to set the method.

    Flask, when it receives the request, will call the appropriate function based on the path and method.