diff --git a/app/__init__.py b/app/__init__.py index 70b4cabfe..aa9cc052c 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -3,5 +3,8 @@ def create_app(test_config=None): app = Flask(__name__) + + from .planets import planets_bp + app.register_blueprint(planets_bp) return app diff --git a/app/planets.py b/app/planets.py new file mode 100644 index 000000000..4b9033ca3 --- /dev/null +++ b/app/planets.py @@ -0,0 +1,49 @@ +from flask import Blueprint, jsonify, abort, make_response + +class Planet(): + def __init__(self, id, name, description): + self.id = id + self.name = name + self.description = description + + def to_dict(self): + return { + "id": self.id, + "name": self.name, + "description": self.description + } + + +planets = [ + Planet(id = 3, name = "Earth", description = "habitable"), + Planet(id = 1, name = "Mercury", description = "inhabitable"), + Planet(id = 4, name = "Mars", description = "inhabitable") +] + +def validate_planet(planet_id): + try: + planet_id = int(planet_id) + except: + abort(make_response({"message": f"Planet {planet_id} is not an int."}, 400)) + + for planet in planets: + if planet.id == planet_id: + return planet + + abort(make_response({"message":f"planet {planet_id} not found"}, 404)) + + +planets_bp = Blueprint("planets_bp", __name__, url_prefix="/planets") + +@planets_bp.route("", methods=["GET"]) +def get_all_planets(): + planet_response = [] + for planet in planets: + planet_response.append(planet.to_dict()) + + return jsonify(planet_response) + +@planets_bp.route("/", methods=["GET"]) +def get_planet_by_id(planet_id): + planet = validate_planet(planet_id) + return jsonify(planet.to_dict())