0
0
FastAPIframework~10 mins

Pagination patterns in FastAPI - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the FastAPI class.

FastAPI
from fastapi import [1]
app = [1]()
Drag options to blanks, or click blank then click option'
AFastAPI
BRequest
CResponse
DDepends
Attempts:
3 left
💡 Hint
Common Mistakes
Importing Request or Response instead of FastAPI.
Forgetting to create the app instance.
2fill in blank
medium

Complete the code to add query parameters for pagination: skip and limit.

FastAPI
@app.get('/items/')
async def read_items(skip: int = [1], limit: int = 10):
    return {'skip': skip, 'limit': limit}
Drag options to blanks, or click blank then click option'
A1
B0
CNone
D-1
Attempts:
3 left
💡 Hint
Common Mistakes
Setting skip default to 1, which skips the first item unintentionally.
Using None as default which causes errors.
3fill in blank
hard

Fix the error in the code to correctly use the Query function for limit with a default and max value.

FastAPI
from fastapi import Query

@app.get('/items/')
async def read_items(limit: int = Query([1], le=100)):
    return {'limit': limit}
Drag options to blanks, or click blank then click option'
ANone
B100
C10
D'10'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a string '10' instead of integer 10.
Using None which causes validation errors.
4fill in blank
hard

Fill both blanks to create a paginated response with skip and limit parameters and return sliced items.

FastAPI
items = ['apple', 'banana', 'cherry', 'date', 'elderberry']

@app.get('/fruits/')
async def get_fruits(skip: int = [1], limit: int = [2]):
    return items[skip:skip + limit]
Drag options to blanks, or click blank then click option'
A0
B5
C10
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Setting skip to 1 which skips the first item.
Setting limit too large or zero.
5fill in blank
hard

Fill all three blanks to implement cursor-based pagination using a query parameter 'cursor' and slicing the items list.

FastAPI
items = ['a', 'b', 'c', 'd', 'e', 'f']

@app.get('/letters/')
async def get_letters(cursor: int = [1], limit: int = [2]):
    start = cursor if cursor >= 0 else 0
    end = start + limit
    return {'items': items[start:end], 'next_cursor': [3] if end < len(items) else None}
Drag options to blanks, or click blank then click option'
A0
B3
Cend
Dcursor + limit
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'end' as next_cursor which is a variable but not the cursor position.
Setting cursor default to negative values.
Using limit as next_cursor.