0
0
Flaskframework~10 mins

API error handling in Flask - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
AFlask
BResponse
CRequest
Djsonify
Attempts:
3 left
💡 Hint
Common Mistakes
Importing Request instead of Flask
Using jsonify instead of Flask
Forgetting to import Flask
2fill in blank
medium

Complete 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'
A403
B200
C500
D404
Attempts:
3 left
💡 Hint
Common Mistakes
Using 200 instead of 404
Using 500 which means server error
Using 403 which means forbidden
3fill in blank
hard

Fix 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'
A404
B403
C400
D500
Attempts:
3 left
💡 Hint
Common Mistakes
Using 404 instead of 400
Using 500 which is server error
Using 403 which means forbidden
4fill in blank
hard

Fill 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'
A404
Bjsonify
Cmake_response
Dabort
Attempts:
3 left
💡 Hint
Common Mistakes
Using jsonify alone without make_response
Using abort inside error handler
Using wrong error code
5fill in blank
hard

Fill 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'
A400
B'Missing name field'
D'Invalid data'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong status code in abort
Not providing a description string
Mismatch between abort code and errorhandler code