Bird
0
0

Consider this code snippet for fetching paginated data using cursor-based pagination:

medium📝 Debug Q14 of 15
Rest API - Pagination Patterns

Consider this code snippet for fetching paginated data using cursor-based pagination:

cursor = None
while True:
    response = api.get_items(cursor=cursor)
    process(response.data)
    cursor = response.next_cursor
    if not cursor:
        break

What is the likely bug in this code?

AIt processes data before fetching
BIt does not check if <code>next_cursor</code> exists before assigning
CIt never updates the cursor value
DIt may cause an infinite loop if <code>next_cursor</code> is empty string
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the code structure

    The code fetches data, processes it, then assigns cursor = response.next_cursor without checking if next_cursor is empty string.
  2. Step 2: Potential infinite loop

    If next_cursor is an empty string, the condition if not cursor will be true and break the loop, so no infinite loop occurs. But if the check is incorrect or cursor is None, it breaks. However, the main issue is if next_cursor is missing, it raises an error.
  3. Step 3: Proper handling

    Should check if next_cursor exists and is truthy before assigning and breaking.
  4. Final Answer:

    It may cause an infinite loop if next_cursor is empty string -> Option D
  5. Quick Check:

    Check for empty or missing cursor carefully [OK]
Quick Trick: Check for empty or missing cursor carefully [OK]
Common Mistakes:
  • Assuming next_cursor always exists
  • Not breaking loop on missing cursor
  • Updating cursor after break

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Rest API Quizzes