Question 24
An API resource created using flask_restful is shown below. Answer the given subquestions if the app is running locally on http://127.0.0.1:5000
from flask import Flask, make_responsefrom flask_restful import Resource, Api, reqparsefrom werkzeug.exceptions import HTTPException
app = Flask(__name__)api = Api(app)
objects = { "bot101": {"obj_code": "BOT01", "obj_name": "bottles"}, "sop109": {"obj_code": "SOP09", "obj_name": "soaps"}, "can103": {"obj_code": "CAN03", "obj_name": "candles"} }
to_parse = reqparse.RequestParser()to_parse.add_argument("obj_code")to_parse.add_argument("obj_name")
class NoObjectError(HTTPException): def __init__(self, status, error): self.response = make_response({"Error": error}, status)
class BadRequest(HTTPException): def __init__(self, status, error): self.response = make_response({"Error": error}, status)
class Objects(Resource): def get(self, id): args = to_parse.parse_args() if id in objects: my_obj = objects[id] if args["obj_code"] == None: raise BadRequest(404, "Object code missing.") if args["obj_name"] == None: raise BadRequest(404, "Object name missing.") else: my_obj["obj_code"] = args["obj_code"] my_obj["obj_name"] = args["obj_name"] return my_obj else: raise NoObjectError(404, "Object doesn't exist in the database.")api.add_resource(Objects, "/get_object/<id>")
app.run(debug = True)