Skip to content

Conversation

@igorbenav
Copy link
Collaborator

Main changes

  • app.api.pagination module created
  • ListResponse and PaginatedListResponse moved to pagination module
  • paginated_response and compute_offset functions created in pagination module
  • api endpoints using get_multi updated to the new structure
  • docs

Docs

With the get_multi method we get a python dict with full suport for pagination:

{
  "data": [
    {
      "id": 4,
      "name": "User Userson",
      "username": "userson4",
      "email": "[email protected]",
      "profile_image_url": "https://profileimageurl.com"
    },
    {
      "id": 5,
      "name": "User Userson",
      "username": "userson5",
      "email": "[email protected]",
      "profile_image_url": "https://profileimageurl.com"
    }
  ],
  "total_count": 2,
  "has_more": false,
  "page": 1,
  "items_per_page": 10
} 

And in the endpoint, we can import from app/api/paginated the following functions and Pydantic Schema:

from app.api.paginated import (
  PaginatedListResponse, # What you'll use as a response_model to validate
  paginated_response,    # Creates a paginated response based on the parameters
  compute_offset         # Calculate the offset for pagination ((page - 1) * items_per_page)
)

Then let's create the endpoint:

import fastapi

from app.schemas.entity imoport EntityRead
...

@router.get("/entities", response_model=PaginatedListResponse[EntityRead])
async def read_entities(
    request: Request, 
    db: Annotated[AsyncSession, Depends(async_get_db)],
    page: int = 1,
    items_per_page: int = 10
):
    entities_data = await crud_entity.get_multi(
        db=db,
        offset=compute_offset(page, items_per_page),
        limit=items_per_page,
        schema_to_select=UserRead, 
        is_deleted=False
    )
    
    return paginated_response(
        crud_data=entities_data, 
        page=page,
        items_per_page=items_per_page
    )

@igorbenav igorbenav added the enhancement New feature or request label Nov 5, 2023
@igorbenav igorbenav self-assigned this Nov 5, 2023
@igorbenav igorbenav merged commit 394c791 into main Nov 5, 2023
@igorbenav igorbenav deleted the paginated-return branch November 5, 2023 04:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants