-1

I think this must be a really simple question or perhaps I'm overlooking something major, but I'm only getting started and there is something I just can't figure out. I wrote a simple flask application:

from flask import Flask, request, jsonify
app = Flask(__name__)

@app.route("/")
def index():
    return "Index!"

@app.route('/test', methods=['GET', 'POST'])
def test():
    if request.method=='GET':
        return "OK this is a get method"

    elif request.method=='POST':
        return "OK this is a post method"
    else:
        return("ok")


if __name__ == "__main__":
    app.run()   

When I open the following URL I get the GET method message as expected.

http://localhost:5000/test

But I can't switch it to a POST method. What URL would I need to enter to see the POST method message?

ADJ
  • 4,892
  • 10
  • 50
  • 83

2 Answers2

2

Whenever you make a direct URL request via browser, it makes a GET call. It is not related to the URL, but the request type value that goes with the request to your server.

In order to make POST request (OR any other type of request) you may use any Rest Client Tool, refer: How do I manually fire HTTP POST requests with Firefox or Chrome?

Personally I use, Postman which comes as plugin for Chrome. Advance Rest Client is also a very nice alternative to achieve this.

If you want a geeky tool (some people consider command line to be geeky ;) ), you may use curl for transferring data with URLs. For making POST request, you have to call it as:

curl -i -X POST -H 'Content-Type: application/json' -d '{"param1": "value1", "param2": "value2"}' http://localhost:5000/test
Community
  • 1
  • 1
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
0

HTML Forms are the primary way that you'd send a post request. Instead of your return "Index" you could instead do:

return '''
    <form method="post" action="/test">
        <input type="text" name="your field"/>
        <button type="submit">Post to your /test!</button>
    </form>
'''

In reality you'd have that form code in a whatever.html file within your template folder and render it with render_template to keep your code smart.

Doobeh
  • 9,280
  • 39
  • 32