post request python flask

Post Request in Python Flask

If you are building a web application with Python Flask, you may need to handle HTTP requests. One such request is the POST request, which is used to submit data to the server for processing. In this tutorial, we will learn how to handle a POST request in Flask using Python.

Creating a Flask Application

To create a Flask application, you need to install the Flask framework first. You can do this by running the following command:


pip install Flask

Next, create a new file called app.py and add the following code:


from flask import Flask, request

app = Flask(__name__)

@app.route('/submit', methods=['POST'])
def submit():
    data = request.form.get('data')
    return f'The submitted data is: {data}'

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

We have created a Flask application that listens for POST requests on the /submit route. When a POST request is received, it calls the submit() function which retrieves the submitted data and returns it as a response.

Sending a POST Request

To send a POST request to our Flask application, we can use the requests library in Python. Here's an example:


import requests

url = 'http://localhost:5000/submit'
data = {'data': 'Hello World!'}
response = requests.post(url, data=data)

print(response.text)

This code sends a POST request to the /submit route with the data parameter set to 'Hello World!'. The response is then printed to the console.

Conclusion

In this tutorial, we learned how to handle a POST request in Python Flask. We created a Flask application that listens for POST requests and returns the submitted data. We also learned how to send a POST request using the requests library in Python.