Search code examples
python-3.xdictionaryflaskflask-restfulkeyerror

Best way to handle KeyError in dictionary when working with Python RESTful API


from flask import Flask, jsonify, request
from flask_restful import Api, Resource
import jsonpickle

app = Flask(__name__)
api = Api(app)

# creating an empty dictionary and initializing user id to 0.. will increment everytime a person makes a POST request
user_dict = {}
user_id = 0


# Define a class and pass it a Resource. These methods require an ID
class User(Resource):
    @staticmethod
    def get(path_user_id):
        return jsonify(jsonpickle.encode(user_dict.get(path_user_id, "This user does not exist")))

When I boot up the server, I go to visit the /users/1 endpoint. Since the dictionary is empty, it doesn't exist. I get thrown a KeyError, so my temporary solution was to change my dictionary accessor from user_dict[path_user_id] to .get(path_user_id, "This user does not exist"). Is there a better way to handle this?

I'm not sure if this is useful or not, but my dictionary consists of integer keys which map to a "Person" class which contains information about the person (name, age, address, etc)


Solution

  • A 404 status code represents "Resource not found", which perfectly suits your use-case

    from flask import abort
    
    ...
    
    def get(path_user_id):
        if path_user_id not in user_dict:
            abort(404)
        ...