-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
62 lines (50 loc) · 1.64 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
from flask import Flask, jsonify
import json
import random
app = Flask(__name__)
# Load quotes from quotes.json
with open("quotes.json", "r") as file:
quotes = json.load(file)
@app.route('/api/quotes', methods=['GET'])
def get_all_quotes():
"""
Retrieve all available quotes from the dataset.
Returns:
JSON response containing all quotes.
"""
return jsonify(quotes)
@app.route('/api/quotes/random', methods=['GET'])
def get_random_quote():
"""
Retrieve a random quote from the dataset.
Returns:
JSON response containing a single random quote.
"""
random_quote = random.choice(quotes)
return jsonify(random_quote)
@app.route('/api/quotes/<int:quote_id>', methods=['GET'])
def get_quote_by_id(quote_id):
"""
Retrieve a specific quote by its ID.
Args:
quote_id (int): The ID of the quote to retrieve.
Returns:
JSON response containing the quote if found, else a 404 error.
"""
quote = next((q for q in quotes if q["id"] == quote_id), None)
if quote:
return jsonify(quote)
return jsonify({"error": "Quote not found"}), 404
@app.route('/', methods=['GET'])
def home():
"""
Default route providing a welcome message and API usage guide.
Returns:
JSON response with a welcome message.
"""
return jsonify({
"message": "Welcome to the Random Quote API! Use /api/quotes to get started."
})
if __name__ == '__main__':
# Run the Flask application on port 5000, accessible from any host.
app.run(host="0.0.0.0", port=5000, debug=True)