92 أسطر
2.7 KiB
Python
92 أسطر
2.7 KiB
Python
# fruit_api.py
|
|
from flask import Flask, jsonify, request
|
|
from datetime import datetime
|
|
import logging
|
|
|
|
app = Flask(__name__)
|
|
|
|
# -----------------------
|
|
# Logging Configuration
|
|
# -----------------------
|
|
LOG_FILE = "fruit_api.log"
|
|
|
|
logging.basicConfig(
|
|
filename=LOG_FILE,
|
|
level=logging.INFO,
|
|
format="%(asctime)s [%(levelname)s] %(message)s",
|
|
)
|
|
|
|
# In-memory database
|
|
fruits = [
|
|
{"id": 1, "name": "Apple", "color": "Red", "price": 1.50, "quantity": 100, "category": "Tropical"},
|
|
{"id": 2, "name": "Banana", "color": "Yellow", "price": 0.75, "quantity": 150, "category": "Tropical"},
|
|
{"id": 3, "name": "Orange", "color": "Orange", "price": 1.20, "quantity": 80, "category": "Citrus"}
|
|
]
|
|
|
|
# -----------------------
|
|
# Logging Hooks
|
|
# -----------------------
|
|
@app.before_request
|
|
def log_request():
|
|
logging.info(
|
|
f"REQUEST: method={request.method} path={request.path} "
|
|
f"args={dict(request.args)} body={request.get_json(silent=True)} "
|
|
f"ip={request.remote_addr}"
|
|
)
|
|
|
|
@app.after_request
|
|
def log_response(response):
|
|
logging.info(
|
|
f"RESPONSE: method={request.method} path={request.path} "
|
|
f"status={response.status_code} ip={request.remote_addr}"
|
|
)
|
|
return response
|
|
|
|
# -----------------------
|
|
# API Endpoints
|
|
# -----------------------
|
|
@app.route('/')
|
|
def home():
|
|
return jsonify({"message": "Fruit Store API", "version": "1.0"})
|
|
|
|
@app.route('/fruits', methods=['GET'])
|
|
def get_all_fruits():
|
|
return jsonify({"fruits": fruits, "total": len(fruits)})
|
|
|
|
@app.route('/fruits/<int:fruit_id>', methods=['GET'])
|
|
def get_fruit(fruit_id):
|
|
fruit = next((f for f in fruits if f['id'] == fruit_id), None)
|
|
if fruit:
|
|
return jsonify({"fruit": fruit})
|
|
return jsonify({"error": "Fruit not found"}), 404
|
|
|
|
@app.route('/fruits', methods=['POST'])
|
|
def create_fruit():
|
|
data = request.get_json()
|
|
if not data or 'name' not in data:
|
|
return jsonify({"error": "Name is required"}), 400
|
|
|
|
new_id = max([f['id'] for f in fruits]) + 1 if fruits else 1
|
|
new_fruit = {
|
|
"id": new_id,
|
|
"name": data['name'],
|
|
"color": data.get('color', 'Unknown'),
|
|
"price": data.get('price', 0.0),
|
|
"quantity": data.get('quantity', 0),
|
|
"category": data.get('category', 'General'),
|
|
"created_at": datetime.now().isoformat()
|
|
}
|
|
fruits.append(new_fruit)
|
|
return jsonify({"message": "Fruit created successfully", "fruit": new_fruit}), 201
|
|
|
|
@app.route('/health', methods=['GET'])
|
|
def health_check():
|
|
return jsonify({"status": "healthy", "service": "fruit-api"})
|
|
|
|
# -----------------------
|
|
# Run API
|
|
# -----------------------
|
|
if __name__ == '__main__':
|
|
print("Fruit API starting on http://localhost:5000")
|
|
app.run(debug=False, host='0.0.0.0', port=5000)
|