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)
400: Bad Request: The request was invalid.When asked for a user that doesn't existThe request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.so shouldn't be used for a syntactically sound request