Create a Flask API that returns random pictures of dishes. Your API should have at least one endpoint that, when called, responds with a random image of a dish.
- Use Flask to create the API
- Implement at least one endpoint that returns a random dish image
- Handle potential errors gracefully
- Include basic documentation for your API in a README file - include how to run the app, what endpoints are available, and, optionally, any fun facts about the dishes you've included
- Have at least 5 dishes
Submit a zip
file containing your entire Flask app including any images on the link provided here
from flask import Flask, jsonify, send_file
import random
import os
app = Flask(__name__)
# Assume we have a directory called 'dishes' with images of dishes
DISHES_DIR = 'dishes'
@app.route('/random-dish', methods=['GET'])
def random_dish():
try:
# Your code here:
# 1. Get a list of all image files in the DISHES_DIR
# 2. Choose a random image from the list
# 3. Return the image file
pass
except Exception as e:
return jsonify({"error": str(e)}), 500
if __name__ == '__main__':
app.run(debug=True)
- Install Flask:
pip install flask
- you should have Python installed already if you went through the instructions - Create a directory called 'dishes' in the same directory as your Python file
- Add some image files of dishes to the 'dishes' directory
- Implement the
random_dish()
function - Run your Flask app:
python your_file_name.py
- Use
os.listdir()
to get a list of files in a directory - Use
random.choice()
to select a random item from a list - Use Flask's
send_file()
function to return image files
- Add an endpoint that allows filtering dishes by type (e.g., /dish/dessert, /dish/main-course) [2 points]
- Add an endpoint that returns a list of all available dishes [2 points]
- ⭐️ Official Flask Documentation
- ⭐️ Simple Flask API Tutorial
- Flask Mega-Tutorial by Miguel Grinberg
- Flask Quickstart
- Real Python Flask Tutorials
- RESTful API Design: Best Practices by Miguel Grinberg
- Flask RESTful Documentation
Remember to consult these resources if you get stuck or want to learn more about specific aspects of Flask and API development. Good luck, and happy coding!