Bird
0
0

Given this Flask route and service layer code, what will be the output when accessing /user/2 if user with ID 2 exists?

medium📝 component behavior Q13 of 15
Flask - Ecosystem and Patterns
Given this Flask route and service layer code, what will be the output when accessing /user/2 if user with ID 2 exists?
from flask import Flask, jsonify
app = Flask(__name__)

class UserService:
    def get_user_by_id(self, user_id):
        users = {1: 'Alice', 2: 'Bob'}
        return users.get(user_id, None)

service = UserService()

@app.route('/user/<int:user_id>')
def user(user_id):
    user_name = service.get_user_by_id(user_id)
    if user_name:
        return jsonify({'user': user_name})
    else:
        return jsonify({'error': 'User not found'}), 404
A{"error": "User not found"}
BServer error due to missing user
C404 Not Found error without JSON
D{"user": "Bob"}
Step-by-Step Solution
Solution:
  1. Step 1: Check user existence in service

    User with ID 2 exists in the dictionary as 'Bob', so get_user_by_id(2) returns 'Bob'.
  2. Step 2: Analyze route response

    Since user_name is truthy, route returns JSON with {'user': 'Bob'} and status 200.
  3. Final Answer:

    {"user": "Bob"} -> Option D
  4. Quick Check:

    User found returns JSON with user name [OK]
Quick Trick: If user exists, route returns JSON with user name [OK]
Common Mistakes:
MISTAKES
  • Assuming 404 error when user exists
  • Confusing JSON error message with missing user
  • Thinking server error occurs without exception

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Flask Quizzes