| Flask is a feature in the Flask web framework (a popular micro web framework for Python). Flask-Flash is used to display flash messages to users. Flash messages are typically used to provide feedback to users, such as notifications about the success or failure of an operation. Here's a simple Flask web server in Python with a basic API. This example will create a server that can handle GET and POST requests. Step 1: Install Flask If you don't have Flask installed, you can install it using pip: pip install Flask
Step 2: Create the Flask Web Server Create a new Python file (e.g., app.py) and add the following code: from flask import Flask, request, jsonify
app = Flask(__name__)
# Define a route for a simple GET request
@app.route('/api/hello', methods=['GET'])
def hello_world():
return jsonify(message="Hello, World!")
# Define a route for a simple POST request
@app.route('/api/data', methods=['POST'])
def get_data():
data = request.get_json()
return jsonify(received_data=data)
if __name__ == '__main__':
app.run(debug=True)
Explanation Importing Flask and necessary modules: from flask import Flask, request, jsonify
Initialize the Flask application: app = Flask(__name__)
Define a route for a GET request: @app.route('/api/hello', methods=['GET'])
def hello_world():
return jsonify(message="Hello, World!")
Define a route for a POST request: @app.route('/api/data', methods=['POST'])
def get_data():
data = request.get_json()
return jsonify(received_data=data)
Run the application: if __name__ == '__main__':
app.run(debug=True)
Running the Server To run the server, navigate to the directory where your app.py is located and execute the following command: python app.py
The server will start running on http://127.0.0.1:5000/. Testing the API You can test the API using tools like curl, Postman, or simply your browser. Testing the GET request: curl http://127.0.0.1:5000/api/hello
You should see the following response: {
"message": "Hello, World!"
}
Testing the POST request: curl -X POST http://127.0.0.1:5000/api/data -H "Content-Type: application/json" -d '{"name": "Levi", "age": 18}'
You should see the following response: {
"received_data": {
"name": "Levi",
"age": 18
}
}
This basic setup can be extended to include |