Bird
Raised Fist0
Rest APIprogramming~20 mins

Graceful degradation in Rest API - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Graceful Degradation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this REST API error handling code?

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?

Rest API
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()
A{"message": "Service temporarily unavailable, please try later"}
B{"error": "Database connection failed"}
C{"user_id": 1, "name": "John Doe"}
D500 Internal Server Error
Attempts:
2 left
💡 Hint

Look at the except block and what JSON it returns.

🧠 Conceptual
intermediate
1:30remaining
Which best describes graceful degradation in REST APIs?

Choose the statement that best explains the concept of graceful degradation in REST APIs.

AThe API provides a simpler or fallback response when some components fail.
BThe API stops working completely when a service fails.
CThe API ignores errors and returns empty responses.
DThe API crashes and returns a 500 error for all requests.
Attempts:
2 left
💡 Hint

Think about how the API behaves when something goes wrong but still tries to respond usefully.

🔧 Debug
advanced
2:30remaining
Why does this graceful degradation code fail to return fallback data?

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?

Rest API
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()
AThe try block should return fallback data directly, not in except.
BThe variable 'fallback' is not defined if no exception occurs, causing a NameError.
CThe jsonify function is called outside the except block, causing a syntax error.
DThe except block does not return a response, so the function returns None.
Attempts:
2 left
💡 Hint

What happens if the try block does not raise an exception?

📝 Syntax
advanced
1:30remaining
Which option fixes the syntax error in this graceful degradation snippet?

Identify the option that fixes the syntax error in this Python REST API snippet using graceful degradation.

Rest API
def fetch_data():
    try
        data = get_remote_data()
    except Exception:
        data = {'message': 'Fallback data'}
    return data
AIndent the except block at the same level as try.
BRemove the except block entirely.
CChange try to try():
DAdd a colon after try: <br> def fetch_data():<br> &nbsp;&nbsp;try:<br> &nbsp;&nbsp;&nbsp;&nbsp;data = get_remote_data()<br> &nbsp;&nbsp;except Exception:<br> &nbsp;&nbsp;&nbsp;&nbsp;data = {'message': 'Fallback data'}<br> &nbsp;&nbsp;return data
Attempts:
2 left
💡 Hint

Check the syntax for try-except blocks in Python.

🚀 Application
expert
2:30remaining
How many fallback responses does this REST API provide?

Given the following Flask REST API code, how many different fallback JSON responses can the API return when the main service fails?

Rest API
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()
A0
B2
C1
D3
Attempts:
2 left
💡 Hint

Which except block will run given the raised exception?

Practice

(1/5)
1. What is the main goal of graceful degradation in REST APIs?
easy
A. To keep the API working even if some parts fail
B. To stop the API immediately when an error occurs
C. To ignore all errors and continue without response
D. To make the API faster by skipping error checks

Solution

  1. Step 1: Understand graceful degradation purpose

    Graceful degradation means the system still works even if some parts fail.
  2. Step 2: Compare options with this meaning

    Only To keep the API working even if some parts fail matches this idea by keeping the API working despite failures.
  3. Final Answer:

    To keep the API working even if some parts fail -> Option A
  4. Quick Check:

    Graceful degradation = keep working despite failure [OK]
Hint: Graceful degradation means continue working despite errors [OK]
Common Mistakes:
  • Thinking it stops the API on error
  • Assuming errors are ignored without response
  • Confusing with performance optimization
2. Which of the following is the correct way to handle errors for graceful degradation in a REST API response (in pseudocode)?
easy
A. ignore errors and return nothing
B. return data; if error then stop
C. try { return data } catch { return fallbackData }
D. throw error without handling

Solution

  1. Step 1: Identify error handling syntax

    Graceful degradation uses try-catch to handle errors and provide fallback data.
  2. Step 2: Match options to this pattern

    try { return data } catch { return fallbackData } shows try-catch with fallback, others either stop or ignore errors.
  3. Final Answer:

    try { return data } catch { return fallbackData } -> Option C
  4. Quick Check:

    Use try-catch with fallback for graceful degradation [OK]
Hint: Use try-catch to return fallback on error [OK]
Common Mistakes:
  • Not catching errors properly
  • Stopping API on first error
  • Ignoring fallback responses
3. Consider this pseudocode for a REST API endpoint:
function getUserData() {
  try {
    return fetchUserFromDB();
  } catch (error) {
    return { name: "Guest", id: 0 };
  }
}

What will getUserData() return if the database fetch fails?
medium
A. An error message
B. Nothing, the function crashes
C. Null
D. A default user object with name 'Guest' and id 0

Solution

  1. Step 1: Analyze try block behavior

    If fetchUserFromDB() works, it returns user data.
  2. Step 2: Analyze catch block fallback

    If an error occurs, catch returns default user object with name 'Guest' and id 0.
  3. Final Answer:

    A default user object with name 'Guest' and id 0 -> Option D
  4. Quick Check:

    Error fallback returns default user object [OK]
Hint: Catch returns default object on failure [OK]
Common Mistakes:
  • Assuming function crashes on error
  • Expecting null instead of fallback object
  • Thinking error message is returned
4. This REST API code snippet is meant to provide graceful degradation but has a bug:
function getData() {
  try {
    return fetchData();
  } catch (error) {
    fallbackData;
  }
}

What is the problem?
medium
A. The try block is missing
B. The fallback data is not returned in the catch block
C. The function does not catch errors
D. The function returns twice

Solution

  1. Step 1: Check catch block code

    The catch block has fallbackData; but does not return it.
  2. Step 2: Understand function return behavior

    Without return, the function returns undefined on error, breaking graceful degradation.
  3. Final Answer:

    The fallback data is not returned in the catch block -> Option B
  4. Quick Check:

    Catch must return fallback data for graceful degradation [OK]
Hint: Always return fallback data inside catch block [OK]
Common Mistakes:
  • Forgetting to return fallback data
  • Misplacing try-catch blocks
  • Assuming catch auto-returns value
5. You have a REST API that fetches user profile and user posts separately. To apply graceful degradation, which approach is best?
hard
A. If fetching posts fails, return profile with empty posts list
B. If fetching posts fails, return error and no profile
C. Stop API if either profile or posts fail
D. Ignore profile and only return posts

Solution

  1. Step 1: Understand graceful degradation in multi-part fetch

    It means returning partial data if one part fails, not stopping all.
  2. Step 2: Evaluate options for partial fallback

    If fetching posts fails, return profile with empty posts list returns profile and empty posts if posts fail, matching graceful degradation.
  3. Final Answer:

    If fetching posts fails, return profile with empty posts list -> Option A
  4. Quick Check:

    Partial data returned on failure = graceful degradation [OK]
Hint: Return partial data with fallback for failed parts [OK]
Common Mistakes:
  • Stopping API on any failure
  • Returning no data if one part fails
  • Ignoring fallback for partial data