Is it possible to make POST request in Flask?

For the record, here's general code to make a POST request from Python:

#make a POST request
import requests
dictToSend = {'question':'what is the answer?'}
res = requests.post('http://localhost:5000/tests/endpoint', json=dictToSend)
print 'response from server:',res.text
dictFromServer = res.json()

Notice that we are passing in a Python dict using the json= option. This conveniently tells the requests library to do two things:

  1. serialize the dict to JSON
  2. write the correct MIME type ('application/json') in the HTTP header

And here's a Flask application that will receive and respond to that POST request:

#handle a POST request
from flask import Flask, render_template, request, url_for, jsonify
app = Flask(__name__)

@app.route('/tests/endpoint', methods=['POST'])
def my_test_endpoint():
    input_json = request.get_json(force=True) 
    # force=True, above, is necessary if another developer 
    # forgot to set the MIME type to 'application/json'
    print 'data from client:', input_json
    dictToReturn = {'answer':42}
    return jsonify(dictToReturn)

if __name__ == '__main__':
    app.run(debug=True)

Yes, to make a POST request you can use urllib, see the documentation.

I would however recommend to use the requests module instead.

EDIT:

I suggest you refactor your code to extract the common functionality:

@app.route("/test", methods=["POST"])
def test():
    return _test(request.form["test"])

@app.route("/index")
def index():
    return _test("My Test Data")

def _test(argument):
    return "TEST: %s" % argument

Tags:

Python

Post

Flask