Bird
Raised Fist0
FastAPIframework~20 mins

Pagination patterns in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Pagination Pro
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this FastAPI pagination endpoint?
Consider this FastAPI endpoint that returns a paginated list of items. What will be the JSON response when requesting page=2 with size=3?
FastAPI
from fastapi import FastAPI, Query
from typing import List

app = FastAPI()

items = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape"]

@app.get("/items/")
async def get_items(page: int = Query(1, ge=1), size: int = Query(3, ge=1)) -> List[str]:
    start = (page - 1) * size
    end = start + size
    return items[start:end]
A["banana", "cherry", "date"]
B["date", "elderberry", "fig"]
C["elderberry", "fig", "grape"]
D["apple", "banana", "cherry"]
Attempts:
2 left
💡 Hint
Calculate the start and end indices for page 2 with size 3.
📝 Syntax
intermediate
2:00remaining
Which option correctly implements limit-offset pagination in FastAPI?
You want to implement limit-offset pagination in FastAPI. Which code snippet correctly returns the paginated items?
FastAPI
items = ["a", "b", "c", "d", "e", "f", "g"]

@app.get("/items/")
async def get_items(limit: int = 3, offset: int = 0):
    # return paginated items here
Areturn items[offset:offset+limit]
Breturn items[limit:offset+limit]
Creturn items[offset:limit]
Dreturn items[limit:offset]
Attempts:
2 left
💡 Hint
Remember slicing syntax: list[start:end]
🔧 Debug
advanced
2:00remaining
Why does this cursor pagination code raise an error?
This FastAPI cursor pagination code raises a TypeError. What is the cause?
FastAPI
from fastapi import FastAPI

app = FastAPI()

items = ["x", "y", "z"]

@app.get("/items/")
async def get_items(cursor: int = None, size: int = 2):
    start = cursor or 0
    end = start + size
    return items[start:end]

# Calling /items/?cursor=abc&size=2 causes the error
AThe items list is empty causing an IndexError
BThe code tries to add an int and a string causing a TypeError inside the function
Ccursor is declared as int but receives a string, causing a validation error before the function runs
DThe default value for cursor is None which cannot be used in arithmetic
Attempts:
2 left
💡 Hint
Check how FastAPI handles query parameter types.
🧠 Conceptual
advanced
2:00remaining
What is a key advantage of cursor pagination over limit-offset pagination?
In FastAPI or any web API, why might you choose cursor pagination instead of limit-offset pagination?
ACursor pagination avoids skipping or repeating items when data changes during pagination
BCursor pagination is simpler to implement and requires less code
CCursor pagination always returns the total count of items
DCursor pagination allows random access to any page by number
Attempts:
2 left
💡 Hint
Think about data consistency when items are added or removed.
❓ state_output
expert
2:00remaining
What is the value of 'next_cursor' after this FastAPI cursor pagination call?
Given this code, what is the value of 'next_cursor' returned when calling /items/?cursor=1&size=2?
FastAPI
from fastapi import FastAPI
from typing import Optional

app = FastAPI()

items = ["a", "b", "c", "d", "e"]

@app.get("/items/")
async def get_items(cursor: Optional[int] = None, size: int = 2):
    start = cursor or 0
    end = start + size
    page_items = items[start:end]
    next_cursor = end if end < len(items) else None
    return {"items": page_items, "next_cursor": next_cursor}
A2
BNone
C1
D3
Attempts:
2 left
💡 Hint
Calculate end index and compare with list length.

Practice

(1/5)
1. What is the main purpose of pagination in a FastAPI application?
easy
A. To split large data sets into smaller, manageable parts
B. To speed up the server hardware
C. To encrypt data before sending it
D. To change the database schema automatically

Solution

  1. Step 1: Understand pagination concept

    Pagination divides large data into smaller chunks to avoid overwhelming users or servers.
  2. Step 2: Identify the main goal in FastAPI

    FastAPI uses pagination to send only a part of data per request, improving performance and usability.
  3. Final Answer:

    To split large data sets into smaller, manageable parts -> Option A
  4. Quick Check:

    Pagination = split data [OK]
Hint: Pagination means breaking data into pages [OK]
Common Mistakes:
  • Thinking pagination speeds up hardware
  • Confusing pagination with encryption
  • Assuming pagination changes database structure
2. Which of the following is the correct way to declare pagination parameters in a FastAPI endpoint using query parameters?
easy
A. def get_items(offset: str = '0', count: str = '10'):
B. def get_items(page: str = '1', size: str = '10'):
C. def get_items(skip: int = 0, limit: int = 10):
D. def get_items(start: int, end: int):

Solution

  1. Step 1: Check parameter types for pagination

    Pagination parameters should be integers with default values for skip and limit.
  2. Step 2: Validate correct syntax in FastAPI

    Using skip and limit as integers with defaults is standard and valid for query parameters.
  3. Final Answer:

    def get_items(skip: int = 0, limit: int = 10): -> Option C
  4. Quick Check:

    skip and limit as int with defaults [OK]
Hint: Use int with defaults for skip and limit [OK]
Common Mistakes:
  • Using strings instead of integers for pagination
  • Missing default values for query parameters
  • Using unclear parameter names like start/end
3. Given this FastAPI endpoint snippet, what will be the output if called with ?skip=2&limit=3 on a list [10, 20, 30, 40, 50, 60]?
items = [10, 20, 30, 40, 50, 60]

@app.get('/items')
def read_items(skip: int = 0, limit: int = 5):
    return items[skip : skip + limit]
medium
A. [40, 50, 60]
B. [20, 30, 40]
C. [10, 20, 30]
D. [30, 40, 50]

Solution

  1. Step 1: Understand slicing with skip and limit

    With skip=2 and limit=3, slice is items[2:5].
  2. Step 2: Extract slice from list

    items[2:5] = [30, 40, 50] from the list.
  3. Final Answer:

    [30, 40, 50] -> Option D
  4. Quick Check:

    items[2:5] = [30, 40, 50] [OK]
Hint: Slice list from skip to skip+limit [OK]
Common Mistakes:
  • Confusing skip with page number
  • Using limit as end index instead of length
  • Off-by-one errors in slicing
4. Identify the error in this FastAPI pagination endpoint:
@app.get('/users')
def get_users(page: int = 1, size: int = 10):
    skip = page * size
    users = get_all_users()
    return users[skip : skip + size]
medium
A. The calculation of skip should be (page - 1) * size
B. The function should use skip and limit parameters instead of page and size
C. The slice should be users[skip : size] instead of users[skip : skip + size]
D. The default size should be 1, not 10

Solution

  1. Step 1: Analyze skip calculation

    Skip should start from zero on page 1, so skip = (page - 1) * size.
  2. Step 2: Check slicing correctness

    Current skip calculation skips too many items, causing wrong slice.
  3. Final Answer:

    The calculation of skip should be (page - 1) * size -> Option A
  4. Quick Check:

    skip = (page - 1) * size [OK]
Hint: Page 1 means skip zero items [OK]
Common Mistakes:
  • Using page * size instead of (page - 1) * size
  • Confusing slice end index
  • Ignoring zero-based indexing
5. You want to create a FastAPI endpoint that returns paginated results along with total count of items. Which of the following code snippets correctly implements this pattern?
hard
A. def get_paginated(page: int = 0, size: int = 10): data = get_all_data() skip = (page - 1) * size return {"total": len(data), "items": data[skip:skip+size]}
B. def get_paginated(skip: int = 0, limit: int = 10): data = get_all_data() return {"total": len(data), "items": data[skip:skip+limit]}
C. def get_paginated(offset: int = 0, count: int = 10): data = get_all_data() return {"total": len(data), "items": data[offset:count]}
D. def get_paginated(page: int = 1, size: int = 10): data = get_all_data() skip = page * size return {"count": len(data), "results": data[skip:skip+size]}

Solution

  1. Step 1: Check pagination calculation

    def get_paginated(skip: int = 0, limit: int = 10): data = get_all_data() return {"total": len(data), "items": data[skip:skip+limit]} correctly uses skip and limit with default values and slices data properly.
  2. Step 2: Verify total count and returned keys

    def get_paginated(skip: int = 0, limit: int = 10): data = get_all_data() return {"total": len(data), "items": data[skip:skip+limit]} returns total count and paginated items with clear keys "total" and "items".
  3. Final Answer:

    def get_paginated(skip: int = 0, limit: int = 10):\n data = get_all_data()\n return {"total": len(data), "items": data[skip:skip+limit]} -> Option B
  4. Quick Check:

    Skip/limit with total count returned [OK]
Hint: Return total count and slice with skip/limit [OK]
Common Mistakes:
  • Wrong skip calculation with page * size
  • Incorrect slice indices causing empty results
  • Using page=0 instead of page=1 for pagination
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