Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to import the Flask class.
Flask
from flask import [1] app = [1](__name__)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Importing Request instead of Flask
Using jsonify instead of Flask
Forgetting to import Flask
✗ Incorrect
You need to import Flask to create the app instance.
2fill in blank
mediumComplete the code to return a JSON error response with status 404.
Flask
from flask import jsonify @app.route('/item/<int:id>') def get_item(id): item = None # pretend we look for item if not item: return jsonify({'error': 'Item not found'}), [1]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 200 instead of 404
Using 500 which means server error
Using 403 which means forbidden
✗ Incorrect
HTTP status code 404 means 'Not Found', which fits this error.
3fill in blank
hardFix the error in the code to handle 400 Bad Request errors globally.
Flask
@app.errorhandler([1]) def bad_request(error): return jsonify({'error': 'Bad request'}), 400
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 404 instead of 400
Using 500 which is server error
Using 403 which means forbidden
✗ Incorrect
The error handler must match the 400 status code to catch bad requests.
4fill in blank
hardFill both blanks to create a custom error handler for 404 errors returning JSON.
Flask
@app.errorhandler([1]) def not_found(error): response = [2]({'error': 'Resource not found'}, 404) return response
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using jsonify alone without make_response
Using abort inside error handler
Using wrong error code
✗ Incorrect
The decorator uses 404 to catch not found errors, and make_response creates a response with JSON and status code.
5fill in blank
hardFill all three blanks to raise a 400 error with a custom message using abort.
Flask
from flask import abort @app.route('/submit', methods=['POST']) def submit(): data = request.json if not data or 'name' not in data: abort([1], description=[2]) return 'Success', 200 @app.errorhandler([3]) def handle_bad_request(e): return jsonify(error=str(e.description)), 400
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong status code in abort
Not providing a description string
Mismatch between abort code and errorhandler code
✗ Incorrect
Use abort with 400 and a description string. The error handler catches 400 errors and returns JSON with the message.