Creating and running a simple Flask application in Python is quite straightforward. Here’s a basic example:
- Install Flask: First, make sure you have Flask installed. You can install it using pip:
pip install Flask Flask-RESTful
2. Create a Flask Application: Create a new Python file, for example, app.py, and add the following
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
3. Run the Application: Run your Flask application by executing the following command in your terminal:
python app.py
When you navigate to http://127.0.0.1:500/ in your web browser, you should see “Hello, World!” displayed. To create a REST API we can use following code:
from flask import Flask, request
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class HelloWorld(Resource):
def get(self):
return {'message': 'Hello, World!'}
def post(self):
data = request.get_json()
return {'you sent': data}, 201
api.add_resource(HelloWorld, '/')
if __name__ == '__main__':
app.run(debug=True)