Bird
Raised Fist0
Flaskframework~20 mins

CRUD operations in Flask - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
CRUD Mastery in Flask
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Flask route when a GET request is made?

Consider this Flask route that handles a GET request to fetch all items from a list.

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

items = ["apple", "banana", "cherry"]

@app.route('/items', methods=['GET'])
def get_items():
    return jsonify(items)

What will the client receive as a response body?

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

items = ["apple", "banana", "cherry"]

@app.route('/items', methods=['GET'])
def get_items():
    return jsonify(items)
A["apple", "banana", "cherry"] as JSON array
BPlain text string: "apple, banana, cherry"
CPython list printed as string: "['apple', 'banana', 'cherry']"
DEmpty JSON object: {}
Attempts:
2 left
💡 Hint

Remember that jsonify converts Python objects to JSON format.

📝 Syntax
intermediate
2:00remaining
Which Flask route code correctly handles creating a new item with POST?

You want to add a new item sent in JSON format to the items list using a POST request.

Which code snippet correctly extracts the JSON data and appends the new item?

Flask
items = []
A
@app.route('/items', methods=['POST'])
def add_item():
    data = request.form
    items.append(data['item'])
    return jsonify({'message': 'Item added'})
B
@app.route('/items', methods=['POST'])
def add_item():
    data = request.json
    items.append(data.item)
    return jsonify({'message': 'Item added'})
C
@app.route('/items', methods=['POST'])
def add_item():
    data = request.get_json()
    items.append(data['item'])
    return jsonify({'message': 'Item added'})
D
@app.route('/items', methods=['POST'])
def add_item():
    data = request.get_data()
    items.append(data['item'])
    return jsonify({'message': 'Item added'})
Attempts:
2 left
💡 Hint

Use the method that parses JSON body from the request.

🔧 Debug
advanced
2:00remaining
Why does this Flask PUT route raise a KeyError?

Given this Flask route to update an item by index, it raises a KeyError when called.

items = ["apple", "banana", "cherry"]

@app.route('/items/', methods=['PUT'])
def update_item(index):
    data = request.get_json()
    items[index] = data['value']
    return jsonify({'message': 'Item updated'})

What is the most likely cause of the KeyError?

Flask
items = ["apple", "banana", "cherry"]
AThe JSON sent does not have the key 'value', causing KeyError
BFlask route decorator syntax is incorrect causing KeyError
Crequest.get_json() returns None causing KeyError
DThe index is out of range causing KeyError
Attempts:
2 left
💡 Hint

Check the keys in the JSON data sent in the request body.

❓ state_output
advanced
2:00remaining
What is the state of the items list after these DELETE requests?

Starting with items = ['apple', 'banana', 'cherry', 'date'], these DELETE requests are made:

@app.route('/items/', methods=['DELETE'])
def delete_item(index):
    items.pop(index)
    return jsonify({'message': 'Deleted'})

# Requests:
# DELETE /items/1
# DELETE /items/2

What is the final content of items after both requests?

Flask
items = ['apple', 'banana', 'cherry', 'date']
A['apple', 'banana']
B['apple', 'cherry', 'date']
C['apple', 'date']
D['apple', 'cherry']
Attempts:
2 left
💡 Hint

Remember that list indexes shift after each pop.

🧠 Conceptual
expert
2:00remaining
Which statement best describes idempotency in RESTful CRUD operations?

In REST APIs, some HTTP methods are idempotent. Which statement correctly explains idempotency in the context of CRUD operations?

AIdempotency means the method always creates a new resource every time it is called.
BAn idempotent method can be called multiple times with the same effect as a single call, like PUT updating a resource.
CPOST is idempotent because it updates existing resources without creating duplicates.
DDELETE is not idempotent because it removes resources permanently.
Attempts:
2 left
💡 Hint

Think about what happens if you repeat the same request multiple times.

Practice

(1/5)
1. What does the 'CRUD' acronym stand for in Flask web development?
easy
A. Cache, Route, User, Data
B. Connect, Run, Upload, Download
C. Code, Render, Use, Deploy
D. Create, Read, Update, Delete

Solution

  1. Step 1: Understand CRUD basics

    CRUD is a common term in web development describing four basic operations on data.
  2. Step 2: Match each letter to its meaning

    C stands for Create, R for Read, U for Update, and D for Delete.
  3. Final Answer:

    Create, Read, Update, Delete -> Option D
  4. Quick Check:

    CRUD = Create, Read, Update, Delete [OK]
Hint: Remember CRUD as the four main data actions [OK]
Common Mistakes:
  • Confusing CRUD with unrelated terms
  • Mixing up the order of operations
  • Thinking CRUD refers to Flask-specific commands
2. Which HTTP method is typically used in Flask to update an existing resource in a CRUD API?
easy
A. PUT
B. POST
C. GET
D. DELETE

Solution

  1. Step 1: Identify HTTP methods for CRUD

    GET is for reading, POST for creating, PUT for updating, DELETE for deleting.
  2. Step 2: Match update operation

    Updating a resource uses the PUT method in RESTful APIs like Flask.
  3. Final Answer:

    PUT -> Option A
  4. Quick Check:

    Update = PUT method [OK]
Hint: Update uses PUT method in REST APIs [OK]
Common Mistakes:
  • Using POST instead of PUT for updates
  • Confusing GET with update actions
  • Using DELETE for updating data
3. Given this Flask route code snippet, what will be the output when a DELETE request is sent to /item/5?
from flask import Flask, jsonify
app = Flask(__name__)
items = {1: 'apple', 5: 'banana'}

@app.route('/item/', methods=['DELETE'])
def delete_item(id):
    if id in items:
        del items[id]
        return jsonify({'message': 'Deleted'}), 200
    else:
        return jsonify({'error': 'Not found'}), 404
medium
A. {"error": "Not found"} with status 404
B. {"message": "Deleted"} with status 200
C. SyntaxError due to missing return statement
D. 500 Internal Server Error

Solution

  1. Step 1: Check if item with id 5 exists

    The dictionary items contains key 5 with value 'banana'.
  2. Step 2: Analyze DELETE request handling

    Since id 5 exists, it is deleted and a JSON message 'Deleted' with status 200 is returned.
  3. Final Answer:

    {"message": "Deleted"} with status 200 -> Option B
  4. Quick Check:

    Item 5 exists, so deletion returns success message [OK]
Hint: Check if key exists before delete to decide response [OK]
Common Mistakes:
  • Assuming item does not exist and returning 404
  • Forgetting to delete the item before returning
  • Confusing status codes for success and error
4. Identify the error in this Flask route for creating a new item:
@app.route('/item', methods=['POST'])
def create_item():
    data = request.json
    items.append(data['name'])
    return jsonify({'message': 'Item added'}), 201
medium
A. Missing import of request from flask
B. Using append on a dictionary instead of a list
C. Incorrect HTTP method for creating resource
D. Returning wrong status code

Solution

  1. Step 1: Check for necessary imports

    The code uses request.json but does not import request from flask.
  2. Step 2: Verify data structure usage

    Assuming items is a list, append is valid; HTTP method POST is correct; status 201 is correct.
  3. Final Answer:

    Missing import of request from flask -> Option A
  4. Quick Check:

    request must be imported to access request.json [OK]
Hint: Always import request to access JSON data in Flask [OK]
Common Mistakes:
  • Forgetting to import request
  • Using append on a dict instead of list
  • Using GET instead of POST for creation
5. You want to implement a Flask route to update an item only if it exists, otherwise return a 404 error. Which code snippet correctly performs this update using JSON data sent in a PUT request? A)
@app.route('/item/', methods=['PUT'])
def update_item(id):
    data = request.json
    items[id] = data['name']
    return jsonify({'message': 'Updated'}), 200
B)
@app.route('/item/', methods=['PUT'])
def update_item(id):
    if id not in items:
        return jsonify({'error': 'Not found'}), 404
    data = request.json
    items[id] = data['name']
    return jsonify({'message': 'Updated'}), 200
C)
@app.route('/item/', methods=['POST'])
def update_item(id):
    data = request.json
    if id in items:
        items[id] = data['name']
    return jsonify({'message': 'Updated'}), 200
D)
@app.route('/item/', methods=['PUT'])
def update_item(id):
    data = request.json
    if id in items:
        items[id] = data['name']
    else:
        items[id] = 'default'
    return jsonify({'message': 'Updated'}), 200
hard
A. Updates without checking existence, always returns 200
B. Uses POST method incorrectly for update
C. Checks existence, updates if found, else returns 404
D. Adds default if not found instead of 404 error

Solution

  1. Step 1: Verify HTTP method and existence check

    Checks existence, updates if found, else returns 404 uses PUT method and checks if id exists before updating.
  2. Step 2: Confirm correct response for missing item

    If id not found, it returns 404 error, which is correct behavior for update.
  3. Final Answer:

    Checks existence, updates if found, else returns 404 -> Option C
  4. Quick Check:

    Update with existence check returns 404 if missing [OK]
Hint: Always check if item exists before update to avoid errors [OK]
Common Mistakes:
  • Not checking if item exists before update
  • Using POST instead of PUT for update
  • Adding default values instead of error on missing item
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard