pythonflaskpost

How to make a simple POST function with flask?


I made a local service to learn flask and trying to write some get/post functions. I have no problem with GET but POST just confused me a bit. What I want to do is when some user send his name as POST request service will return as "Hello name". I made some research but everything I saw was so complicated and full of json. I do not want to use json because I just send a string and return a string. Can you guys just help me with that and tell me how can I test that post request on curl? Thanks in advance!

Edit: I tried to write my data in json format as

data = { "name" : " "}

and tried to post like

@app.route("/f",methods=['POST'])
def f():
    request_data = request.get_json()
    myName = request_data['name']
    return (str(myName))

but did not work.


Solution

  • Step 1: Install Flask

    pip3 install flask
    

    Step 2: Create a file app.py with:

    from flask import Flask, request
    app = Flask(__name__)
    
    @app.route('/', methods = ['POST'])
    def data():
        rq = request.form
    
        return 'Hello ' + rq.get('name', 'No name')
    

    Step 3: Start Flask

    export FLASK_APP=hello.py
    flask run
    

    Step 4: Call the app with cURL

    curl -X POST http://127.0.0.1:5000/ -d "name=Bob"
    

    ->

    Hello Bob
    

    Json alternative:

    from flask import Flask, request
    app = Flask(__name__)
    
    @app.route('/', methods = ['POST'])
    def data():
        rq = request.get_json()
    
        return 'Hello ' + rq.get('name', 'No name')
    

    Then the cURL would be:

    curl -X POST http://127.0.0.1:5000/ \
      -H "Content-Type: application/json" \
      -d '{"name": "Bob"}'
    

    ->

    Hello Bob