Flask API Code
- User
Flask API Code
- Assistant
Flask API Code
Creating a Flask API involves setting up a basic Flask application with some routes that respond to HTTP requests. Here’s a simple example that demonstrates how to create a basic Flask API:
Install Flask: First, ensure that Flask is installed in your Python environment. You can install it using pip:
pip install Flask
Create the Flask Application: Create a new Python file, for example, app.py and add the following code:
from flask import Flask, jsonify, request
app = Flask(__name__)
# Sample data
items = [
{"id": 1, "name": "Item One", "price": 15.99},
{"id": 2, "name": "Item Two", "price": 29.99}
]
@app.route('/')
def home():
return "Welcome to the Flask API!"
@app.route('/items', methods=['GET'])
def get_items():
return jsonify(items)
@app.route('/items/<int:item_id>', methods=['GET'])
def get_item(item_id):
item = next((item for item in items if item["id"] == item_id), None)
if item is not None:
return jsonify(item)
else:
return jsonify({"error": "Item not found"}), 404
@app.route('/items', methods=['POST'])
def create_item():
new_item = request.get_json()
items.append(new_item)
return jsonify(new_item), 201
@app.route('/items/<int:item_id>', methods=['PUT'])
def update_item(item_id):
item = next((item for item in items if item["id"] == item_id), None)
if item is not None:
update_data = request.get_json()
item.update(update_data)
return jsonify(item)
else:
return jsonify({"error": "Item not found"}), 404
@app.route('/items/<int:item_id>', methods=['DELETE'])
def delete_item(item_id):
global items
items = [item for item in items if item["id"] != item_id]
return jsonify({"message": "Item deleted"}), 200
if __name__ == "__main__":
app.run(debug=True)
Basic Setup: We import Flask, jsonify, and request and create an instance of the Flask class.
Sample Data: We use a sample list of items to act as our in-memory database for demonstration purposes.
Routes:
Running the Application: When the script is executed directly, the Flask application runs in debug mode, allowing for easy testing and debugging.
To run your Flask API, execute the app.py script:
python app.py
After running the script, your Flask API will be accessible at http://127.0.0.1:5000/, and you can test the API endpoints using tools like Postman, curl, or directly through a web browser for GET requests.
Remember, the example above uses an in-memory list as a "database." In a production scenario, you'd likely want to connect to a real database, handle errors more gracefully, and add authentication and logging features.
Not yet included in a published release.