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?
from flask import Flask, jsonify app = Flask(__name__) items = ["apple", "banana", "cherry"] @app.route('/items', methods=['GET']) def get_items(): return jsonify(items)
Remember that jsonify converts Python objects to JSON format.
The jsonify function converts the Python list items into a JSON array. So the client receives a JSON array with the strings.
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?
items = []
Use the method that parses JSON body from the request.
request.get_json() correctly parses JSON data sent in the POST body. Accessing data['item'] gets the new item string.
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?
items = ["apple", "banana", "cherry"]
Check the keys in the JSON data sent in the request body.
If the JSON body lacks the 'value' key, accessing data['value'] raises a KeyError.
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?
items = ['apple', 'banana', 'cherry', 'date']
Remember that list indexes shift after each pop.
First DELETE removes index 1 ('banana'), list becomes ['apple', 'cherry', 'date']. Second DELETE removes index 2 ('date'). Final list: ['apple', 'cherry'].
In REST APIs, some HTTP methods are idempotent. Which statement correctly explains idempotency in the context of CRUD operations?
Think about what happens if you repeat the same request multiple times.
PUT is idempotent because updating a resource multiple times with the same data results in the same state. POST creates new resources and is not idempotent. DELETE is idempotent because deleting the same resource multiple times has the same effect as deleting once.