Adding Swagger Docs endpoint & API Test Script
هذا الالتزام موجود في:
256
fruit_api.py
256
fruit_api.py
@@ -1,91 +1,217 @@
|
||||
# fruit_api.py
|
||||
from flask import Flask, jsonify, request
|
||||
from flask import Flask, request, jsonify
|
||||
from flasgger import Swagger
|
||||
from datetime import datetime
|
||||
import logging
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# -----------------------
|
||||
# Logging Configuration
|
||||
# -----------------------
|
||||
LOG_FILE = "fruit_api.log"
|
||||
# Swagger configuration (serve UI at /docs)
|
||||
app.config["SWAGGER"] = {
|
||||
"title": "Ahmed Gamal's Fruit API",
|
||||
"uiversion": 3,
|
||||
"swagger_ui": True,
|
||||
"specs_route": "/docs/" # force Swagger UI to mount at /docs
|
||||
}
|
||||
swagger = Swagger(app)
|
||||
|
||||
logging.basicConfig(
|
||||
filename=LOG_FILE,
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s [%(levelname)s] %(message)s",
|
||||
)
|
||||
# Root endpoint (http://localhost:5000/)
|
||||
@app.route("/", methods=["GET"])
|
||||
def home():
|
||||
return jsonify({
|
||||
"message": "Welcome to Ahmed Gamal's Fruit API 🚀",
|
||||
"docs_url": "/docs"
|
||||
})
|
||||
|
||||
# In-memory database
|
||||
# Sample data
|
||||
fruits = [
|
||||
{"id": 1, "name": "Apple", "color": "Red", "price": 1.50, "quantity": 100, "category": "Tropical"},
|
||||
{"id": 1, "name": "Apple", "color": "Red", "price": 1.5, "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"}
|
||||
{"id": 3, "name": "Orange", "color": "Orange", "price": 1.2, "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.route("/health", methods=["GET"])
|
||||
def health():
|
||||
"""
|
||||
Health Check
|
||||
---
|
||||
tags:
|
||||
- Health
|
||||
responses:
|
||||
200:
|
||||
description: API is healthy
|
||||
"""
|
||||
return jsonify({
|
||||
"service": "fruit-api",
|
||||
"status": "healthy",
|
||||
"timestamp": datetime.utcnow().isoformat()
|
||||
})
|
||||
|
||||
@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():
|
||||
@app.route("/fruits", methods=["GET"])
|
||||
def get_fruits():
|
||||
"""
|
||||
Get All Fruits
|
||||
---
|
||||
tags:
|
||||
- Fruits
|
||||
responses:
|
||||
200:
|
||||
description: A list of all fruits
|
||||
"""
|
||||
return jsonify({"fruits": fruits, "total": len(fruits)})
|
||||
|
||||
@app.route('/fruits/<int:fruit_id>', methods=['GET'])
|
||||
@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)
|
||||
"""
|
||||
Get a Fruit by ID
|
||||
---
|
||||
tags:
|
||||
- Fruits
|
||||
parameters:
|
||||
- name: fruit_id
|
||||
in: path
|
||||
type: integer
|
||||
required: true
|
||||
responses:
|
||||
200:
|
||||
description: Fruit details
|
||||
404:
|
||||
description: Fruit not found
|
||||
"""
|
||||
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'])
|
||||
@app.route("/fruits", methods=["POST"])
|
||||
def create_fruit():
|
||||
"""
|
||||
Create a New Fruit
|
||||
---
|
||||
tags:
|
||||
- Fruits
|
||||
parameters:
|
||||
- name: body
|
||||
in: body
|
||||
required: true
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
name: {type: string}
|
||||
color: {type: string}
|
||||
price: {type: number}
|
||||
quantity: {type: integer}
|
||||
category: {type: string}
|
||||
responses:
|
||||
201:
|
||||
description: Fruit created
|
||||
"""
|
||||
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()
|
||||
"id": len(fruits) + 1,
|
||||
"name": data.get("name"),
|
||||
"color": data.get("color"),
|
||||
"price": data.get("price"),
|
||||
"quantity": data.get("quantity"),
|
||||
"category": data.get("category"),
|
||||
"created_at": datetime.utcnow().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"})
|
||||
@app.route("/fruits/<int:fruit_id>", methods=["PUT"])
|
||||
def update_fruit(fruit_id):
|
||||
"""
|
||||
Update a Fruit
|
||||
---
|
||||
tags:
|
||||
- Fruits
|
||||
parameters:
|
||||
- name: fruit_id
|
||||
in: path
|
||||
type: integer
|
||||
required: true
|
||||
- name: body
|
||||
in: body
|
||||
required: true
|
||||
schema:
|
||||
type: object
|
||||
responses:
|
||||
200:
|
||||
description: Fruit updated
|
||||
404:
|
||||
description: Fruit not found
|
||||
"""
|
||||
fruit = next((f for f in fruits if f["id"] == fruit_id), None)
|
||||
if not fruit:
|
||||
return jsonify({"error": "Fruit not found"}), 404
|
||||
|
||||
# -----------------------
|
||||
# Run API
|
||||
# -----------------------
|
||||
if __name__ == '__main__':
|
||||
print("Fruit API starting on http://localhost:5000")
|
||||
app.run(debug=False, host='0.0.0.0', port=5000)
|
||||
data = request.get_json()
|
||||
fruit.update(data)
|
||||
fruit["updated_at"] = datetime.utcnow().isoformat()
|
||||
return jsonify({"message": "Fruit updated successfully", "fruit": fruit})
|
||||
|
||||
@app.route("/fruits/<int:fruit_id>", methods=["DELETE"])
|
||||
def delete_fruit(fruit_id):
|
||||
"""
|
||||
Delete a Fruit
|
||||
---
|
||||
tags:
|
||||
- Fruits
|
||||
parameters:
|
||||
- name: fruit_id
|
||||
in: path
|
||||
type: integer
|
||||
required: true
|
||||
responses:
|
||||
200:
|
||||
description: Fruit deleted
|
||||
404:
|
||||
description: Fruit not found
|
||||
"""
|
||||
global fruits
|
||||
fruit = next((f for f in fruits if f["id"] == fruit_id), None)
|
||||
if not fruit:
|
||||
return jsonify({"error": "Fruit not found"}), 404
|
||||
fruits = [f for f in fruits if f["id"] != fruit_id]
|
||||
return jsonify({"message": "Fruit deleted successfully", "deleted_fruit": fruit})
|
||||
|
||||
@app.route("/fruits/search", methods=["GET"])
|
||||
def search_fruits():
|
||||
"""
|
||||
Search Fruits by Name
|
||||
---
|
||||
tags:
|
||||
- Fruits
|
||||
parameters:
|
||||
- name: name
|
||||
in: query
|
||||
type: string
|
||||
required: true
|
||||
responses:
|
||||
200:
|
||||
description: Search results
|
||||
"""
|
||||
name = request.args.get("name", "").lower()
|
||||
results = [f for f in fruits if name in f["name"].lower()]
|
||||
return jsonify({"search_term": name, "count": len(results), "results": results})
|
||||
|
||||
@app.route("/fruits/category/<string:category>", methods=["GET"])
|
||||
def get_fruits_by_category(category):
|
||||
"""
|
||||
Get Fruits by Category
|
||||
---
|
||||
tags:
|
||||
- Fruits
|
||||
parameters:
|
||||
- name: category
|
||||
in: path
|
||||
type: string
|
||||
required: true
|
||||
responses:
|
||||
200:
|
||||
description: Fruits by category
|
||||
"""
|
||||
results = [f for f in fruits if f["category"].lower() == category.lower()]
|
||||
return jsonify({"category": category, "count": len(results), "fruits": results})
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(debug=True, host="0.0.0.0", port=5000)
|
||||
|
المرجع في مشكلة جديدة
حظر مستخدم