Bird
0
0

Which of the following code snippets correctly achieves this?

hard📝 Application Q8 of 15
Rest API - HTTP Status Codes
You are implementing a Flask REST API endpoint to fetch a movie by its ID. If the movie does not exist, you want to return a 404 status with a JSON error message. Which of the following code snippets correctly achieves this?
from flask import Flask, jsonify, abort
app = Flask(__name__)

@app.route('/movies/')
def get_movie(id):
    movies = {1: 'Inception', 2: 'Interstellar'}
    # Which code correctly returns 404 with JSON if movie missing?
Aif id not in movies: abort(404) return jsonify({'movie': movies[id]})
Bif id not in movies: return jsonify({'error': 'Movie not found'}), 404 return jsonify({'movie': movies[id]})
Cif id not in movies: return 'Movie not found', 404 return jsonify({'movie': movies[id]})
Dif id not in movies: return jsonify({'message': 'Movie missing'}) return jsonify({'movie': movies[id]})
Step-by-Step Solution
Solution:
  1. Step 1: Return JSON with 404

    if id not in movies: return jsonify({'error': 'Movie not found'}), 404 return jsonify({'movie': movies[id]}) returns a JSON object with error message and sets status 404 explicitly.
  2. Step 2: Compare other options

    if id not in movies: abort(404) return jsonify({'movie': movies[id]}) aborts with 404 but returns default HTML, not JSON.
    if id not in movies: return 'Movie not found', 404 return jsonify({'movie': movies[id]}) returns plain text, not JSON.
    if id not in movies: return jsonify({'message': 'Movie missing'}) return jsonify({'movie': movies[id]}) returns JSON but no 404 status.
  3. Final Answer:

    if id not in movies: return jsonify({'error': 'Movie not found'}), 404 return jsonify({'movie': movies[id]}) correctly returns JSON and 404 status.
  4. Quick Check:

    Return JSON + 404 status for missing resource. [OK]
Quick Trick: Use jsonify with status code for JSON 404 responses [OK]
Common Mistakes:
MISTAKES
  • Using abort(404) without JSON response
  • Returning plain text instead of JSON
  • Not setting 404 status code when resource missing

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Rest API Quizzes