Consider this Flask route:
from flask import Flask, request
app = Flask(__name__)
@app.route('/data', methods=['GET', 'POST'])
def data():
if request.method == 'POST':
return 'Posted Data'
else:
return 'Got Data'What will the server respond with when a GET request is sent to /data?
from flask import Flask, request app = Flask(__name__) @app.route('/data', methods=['GET', 'POST']) def data(): if request.method == 'POST': return 'Posted Data' else: return 'Got Data'
Think about which method triggers which return statement.
The route accepts both GET and POST. When the method is GET, the else branch runs, returning 'Got Data'.
Choose the correct Flask route decorator to handle PUT requests on the path /update.
Check the spelling and type of the methods argument.
The methods argument must be a list of uppercase HTTP method strings. Option A is correct.
Given this Flask route:
@app.route('/item', methods=['GET', 'POST'])
def item():
return 'Item endpoint'What happens if a client sends a DELETE request to /item?
@app.route('/item', methods=['GET', 'POST']) def item(): return 'Item endpoint'
Check which methods are allowed by the route.
The route only allows GET and POST. DELETE is not allowed, so Flask returns a 405 error.
Consider this Flask app snippet:
from flask import Flask, request
app = Flask(__name__)
items = []
@app.route('/add', methods=['POST'])
def add():
items.append(request.json.get('item'))
return 'Added'If the client sends these requests in order:
- POST to
/addwith JSON{"item": "apple"} - POST to
/addwith JSON{"item": "banana"} - GET to
/add
What is the value of items after these requests?
from flask import Flask, request app = Flask(__name__) items = [] @app.route('/add', methods=['POST']) def add(): items.append(request.json.get('item')) return 'Added'
Remember that GET requests to this route are not handled.
Both POST requests add items to the list. The GET request does nothing to the list because it is not handled.
In REST API design, which HTTP method is considered both idempotent and safe?
Safe means it does not change server state. Idempotent means multiple identical requests have the same effect as one.
GET requests do not change data (safe) and can be repeated without side effects (idempotent). POST is not idempotent or safe. PUT and DELETE are idempotent but not safe.