0
0
Flaskframework~10 mins

HTTP status codes for APIs 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 return a 200 OK status in a Flask API response.

Flask
from flask import Flask, jsonify
app = Flask(__name__)

@app.route('/status')
def status():
    return jsonify({'message': 'Success'}), [1]
Drag options to blanks, or click blank then click option'
A200
B301
C500
D404
Attempts:
3 left
💡 Hint
Common Mistakes
Using 404 which means Not Found
Using 500 which means Server Error
2fill in blank
medium

Complete the code to return a 404 Not Found status when a resource is missing.

Flask
from flask import Flask, jsonify
app = Flask(__name__)

@app.route('/item/<int:id>')
def get_item(id):
    item = None  # pretend we looked for the item
    if not item:
        return jsonify({'error': 'Item not found'}), [1]
Drag options to blanks, or click blank then click option'
A404
B400
C201
D403
Attempts:
3 left
💡 Hint
Common Mistakes
Using 201 which means Created
Using 400 which means Bad Request
3fill in blank
hard

Fix the error in the code to return a 201 Created status after adding a new resource.

Flask
from flask import Flask, jsonify, request
app = Flask(__name__)

@app.route('/add', methods=['POST'])
def add_item():
    data = request.json
    # pretend we add the item here
    return jsonify({'message': 'Item added'}), [1]
Drag options to blanks, or click blank then click option'
A400
B200
C201
D500
Attempts:
3 left
💡 Hint
Common Mistakes
Using 200 which means OK but not specific for creation
Using 400 which means Bad Request
4fill in blank
hard

Fill both blanks to return a 400 Bad Request status with a JSON error message.

Flask
from flask import Flask, jsonify, request
app = Flask(__name__)

@app.route('/submit', methods=['POST'])
def submit():
    data = request.json
    if not data or 'name' not in data:
        return jsonify({'error': [1]), [2]
Drag options to blanks, or click blank then click option'
A'Missing name field'
B400
C200
D'Success'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 200 which means OK
Using a success message instead of an error
5fill in blank
hard

Fill all three blanks to return a 403 Forbidden status with a JSON error message and a custom header.

Flask
from flask import Flask, jsonify, make_response
app = Flask(__name__)

@app.route('/admin')
def admin():
    response = make_response(jsonify({'error': [1]), [2])
    response.headers['X-Reason'] = [3]
    return response
Drag options to blanks, or click blank then click option'
A'Access denied'
B403
C'User not authorized'
D200
Attempts:
3 left
💡 Hint
Common Mistakes
Using 200 which means OK
Using wrong or missing error messages