Consider a REST API endpoint that tries to fetch user data. If the database is down, it returns a fallback message. What will be the JSON response when the database is unreachable?
from flask import Flask, jsonify app = Flask(__name__) @app.route('/user/<int:user_id>') def get_user(user_id): try: # Simulate database call raise ConnectionError('DB down') except ConnectionError: return jsonify({'message': 'Service temporarily unavailable, please try later'}), 503 if __name__ == '__main__': app.run()
Look at the except block and what JSON it returns.
The code catches the database connection error and returns a JSON message with a 503 status code. So the output is the JSON with the message about temporary unavailability.
Choose the statement that best explains the concept of graceful degradation in REST APIs.
Think about how the API behaves when something goes wrong but still tries to respond usefully.
Graceful degradation means the API still works in a limited way, providing fallback data or messages instead of failing completely.
Examine the following Flask REST API code. It is supposed to return fallback data if the main service fails. Why does it not return the fallback data?
from flask import Flask, jsonify app = Flask(__name__) @app.route('/data') def get_data(): try: # Simulate failure raise Exception('Service error') except Exception: fallback = {'data': 'default'} return jsonify(fallback) if __name__ == '__main__': app.run()
What happens if the try block does not raise an exception?
If no exception occurs, the variable 'fallback' is never assigned, so the return statement tries to jsonify an undefined variable, causing a NameError.
Identify the option that fixes the syntax error in this Python REST API snippet using graceful degradation.
def fetch_data(): try data = get_remote_data() except Exception: data = {'message': 'Fallback data'} return data
Check the syntax for try-except blocks in Python.
The try statement must end with a colon. Option D adds the missing colon, fixing the syntax error.
Given the following Flask REST API code, how many different fallback JSON responses can the API return when the main service fails?
from flask import Flask, jsonify app = Flask(__name__) @app.route('/info') def info(): try: # Simulate service failure raise ValueError('Service error') except ValueError: return jsonify({'error': 'Service temporarily unavailable'}), 503 except Exception: return jsonify({'error': 'Unknown error occurred'}), 500 if __name__ == '__main__': app.run()
Which except block will run given the raised exception?
The code raises a ValueError, so only the first except block runs, returning one fallback response.