1
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)

2
  • 1
    I would think that the server itself should be returning a 400: Bad Request: The request was invalid. When asked for a user that doesn't exist Commented May 1, 2019 at 17:13
  • 1
    According to the HTTP status code definition, 400 represents The 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 Commented May 1, 2019 at 17:19

1 Answer 1

3

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)
    ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.