Bird
Raised Fist0
Rest APIprogramming~20 mins

Retry and failure handling in Rest API - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Retry 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 retry logic snippet?

Consider this pseudocode for retrying a REST API call up to 3 times on failure. What will be the final output if the API fails twice and succeeds on the third try?

Rest API
attempts = 0
max_attempts = 3
success = False
while attempts < max_attempts and not success:
    attempts += 1
    if attempts < 3:
        print(f"Attempt {attempts}: Failed")
    else:
        print(f"Attempt {attempts}: Success")
        success = True
if success:
    print("Result: Success")
else:
    print("Result: Failure")
AAttempt 1: Failed\nAttempt 2: Failed\nAttempt 3: Success\nResult: Success
BAttempt 1: Failed\nAttempt 2: Failed\nResult: Failure
CAttempt 1: Failed\nAttempt 2: Success\nResult: Success
DAttempt 1: Success\nResult: Success
Attempts:
2 left
💡 Hint

Look at how the loop increments attempts and when it sets success to True.

🧠 Conceptual
intermediate
1:30remaining
Which HTTP status code should trigger a retry in REST API calls?

When implementing retry logic for REST API calls, which HTTP status code is generally appropriate to trigger a retry?

A200 OK
B500 Internal Server Error
C404 Not Found
D401 Unauthorized
Attempts:
2 left
💡 Hint

Think about server errors vs client errors.

🔧 Debug
advanced
2:30remaining
Why does this retry code cause an infinite loop?

Examine the following retry code snippet. Why does it cause an infinite loop?

Rest API
max_retries = 3
retry_count = 0
success = False
while not success:
    try:
        # simulate API call
        if retry_count < max_retries:
            raise Exception("API failure")
        else:
            success = True
    except Exception as e:
        print(f"Retry {retry_count}: {e}")
Amax_retries is too high causing long loops
BException is not caught properly
Csuccess is never set to True inside the try block
Dretry_count is never incremented, so the loop never ends
Attempts:
2 left
💡 Hint

Check if the retry_count changes inside the loop.

📝 Syntax
advanced
2:30remaining
What error does this retry decorator code raise?

Consider this Python decorator for retrying a function. What error will it raise when used?

Rest API
def retry(func):
    def wrapper(*args, **kwargs):
        for i in range(3):
            try:
                return func(*args, **kwargs)
            except Exception:
                pass
        return wrapper

@retry
def fail_once():
    fail_once.counter += 1
    if fail_once.counter < 2:
        raise Exception("Fail")
    return "Success"

fail_once.counter = 0
print(fail_once())
AAttributeError: 'function' object has no attribute 'counter'
BTypeError: 'function' object is not iterable
CRecursionError: maximum recursion depth exceeded
DNone (prints 'Success')
Attempts:
2 left
💡 Hint

Look at what the decorator returns after retries fail.

🚀 Application
expert
3:00remaining
How many times will the API be called in this exponential backoff retry?

Given this pseudocode implementing exponential backoff retry for a REST API call, how many times will the API be called before the function returns?

Rest API
def call_api_with_retry():
    max_attempts = 4
    delay = 1
    for attempt in range(1, max_attempts + 1):
        response = api_call()
        if response == 'success':
            return attempt
        else:
            sleep(delay)
            delay *= 2
    return max_attempts

# Assume api_call() returns 'fail' for first 3 calls, then 'success' on 4th call.
A4
B3
C5
D1
Attempts:
2 left
💡 Hint

Count how many times the loop runs until success.

Practice

(1/5)
1.

What is the main purpose of retry and failure handling in REST API calls?

easy
A. To speed up the API response time
B. To ignore errors and continue without notification
C. To automatically try the request again if it fails
D. To permanently stop the app on first failure

Solution

  1. Step 1: Understand retry purpose

    Retry means trying the same request again if it fails, to handle temporary issues.
  2. Step 2: Compare options

    Only To automatically try the request again if it fails describes retry correctly. Others describe wrong or harmful behaviors.
  3. Final Answer:

    To automatically try the request again if it fails -> Option C
  4. Quick Check:

    Retry = try again [OK]
Hint: Retry means trying again after failure [OK]
Common Mistakes:
  • Thinking retry speeds up response
  • Ignoring errors without handling
  • Stopping app immediately on failure
2.

Which of the following is the correct way to set a maximum retry count in a REST API client configuration?

retry_config = {
    'max_retries': ?
}
easy
A. 'max_retry': 5
B. 'max_retries': 5
C. 'maxRetries': 5
D. 'max-retries': 5

Solution

  1. Step 1: Identify correct key name

    The standard key for retry count is 'max_retries' with underscore.
  2. Step 2: Check option values

    'max_retries': 5 uses correct key and value format. Others use wrong keys or casing.
  3. Final Answer:

    'max_retries': 5 -> Option B
  4. Quick Check:

    Correct key is max_retries [OK]
Hint: Use underscores for config keys like max_retries [OK]
Common Mistakes:
  • Using camelCase instead of snake_case
  • Misspelling the key as max_retry
  • Using hyphens in keys
3.

Consider this Python code snippet for retrying a REST API call:

import time

def call_api():
    for attempt in range(3):
        response = make_request()
        if response.status_code == 200:
            return 'Success'
        time.sleep(1)
    return 'Failed'

What will be the output if all three requests fail with status code 500?

medium
A. "Success"
B. An exception is raised
C. The function runs forever
D. "Failed"

Solution

  1. Step 1: Analyze retry loop behavior

    The loop tries 3 times. If status_code is 200, returns 'Success'. Otherwise, waits 1 second and retries.
  2. Step 2: Check failure case

    All attempts return 500, so loop finishes without returning 'Success'. Then returns 'Failed'.
  3. Final Answer:

    "Failed" -> Option D
  4. Quick Check:

    All fail -> return 'Failed' [OK]
Hint: If no success in retries, function returns failure [OK]
Common Mistakes:
  • Assuming success on failure status
  • Expecting infinite loop
  • Thinking exception is raised automatically
4.

Find the error in this retry logic snippet:

def fetch_data():
    retries = 3
    while retries > 0:
        response = api_call()
        if response.status_code == 200:
            return response.data
        retries -= 1
    return None
    retries -= 1
medium
A. The last line decreases retries after return, unreachable code
B. Missing sleep between retries
C. No check for network exceptions
D. Should use for loop instead of while

Solution

  1. Step 1: Review code flow

    The last line retries -= 1 is after return None, so it never runs.
  2. Step 2: Identify unreachable code problem

    Code after return is unreachable and unnecessary, indicating a logic error.
  3. Final Answer:

    The last line decreases retries after return, unreachable code -> Option A
  4. Quick Check:

    Code after return is unreachable [OK]
Hint: Code after return is never executed [OK]
Common Mistakes:
  • Ignoring unreachable code warnings
  • Forgetting to add wait between retries
  • Not handling exceptions
5.

You want to implement retry logic that tries up to 4 times with increasing wait times: 1s, 2s, 4s, then stops. Which code snippet correctly implements this?

Option A:
for i in range(3):
    response = call_api()
    if response.ok:
        break
    time.sleep(2 ** i)

Option B:
for i in range(1, 5):
    response = call_api()
    if response.ok:
        break
    time.sleep(i)

Option C:
for i in range(4):
    response = call_api()
    if response.ok:
        break
    time.sleep(i)

Option D:
for i in range(4):
    response = call_api()
    if response.ok:
        break
    time.sleep(2 * i)
hard
A. Option A
B. Option B
C. Option C
D. Option D

Solution

  1. Step 1: Understand wait time pattern

    Wait times should double each retry: 1s, 2s, 4s, then stop after 4 tries.
  2. Step 2: Check the options' sleep times

    The code with time.sleep(2 ** i) and range(3) gives waits of 1s (i=0), 2s (i=1), 4s (i=2). This matches exponential backoff for up to 4 tries (3 retries after initial call).
  3. Step 3: Compare distractors

    The range(1,5) with time.sleep(i) uses linear 1,2,3,4s. range(4) with time.sleep(i) uses 0,1,2,3s. time.sleep(2 * i) uses 0,2,4,6s. None match doubling from 1s.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Exponential backoff uses 2 ** i [OK]
Hint: Use 2 ** i for doubling wait times [OK]
Common Mistakes:
  • Starting wait time at 0 seconds
  • Using linear instead of exponential waits
  • Not stopping after max retries
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