ajyadav013/claude-kit/api-pagination-filtering-sorting
Claude Code and agent skill by ajyadav013/claude-kit
Trust tier 3
- community
Source check pending
Checking that the SKILL.md file is still in the repository.
HTTP query parameter conventions for pagination, filtering, sorting, and search with standardized response metadata. Use when designing list endpoints or building repositories that turn query params into SQL.
Install
npx vskill@latest install ajyadav013/claude-kit/api-pagination-filtering-sortingSKILL.md
The same SKILL.md was published earlier as ajyadav013/claude-kit/api-pagination-filtering-sorting.
Standardize HTTP query parameter conventions and response metadata for paginated, filtered, and sorted list endpoints.
When to use
- Designing a new list endpoint with pagination, filtering, or sorting
- Implementing multi-value or hierarchical filters (e.g., segment, family, class filters)
- Building repository/query builder layers that translate query params to SQL
- Adding search across multiple fields to a list endpoint
- Standardizing response metadata across paginated endpoints
- Reviewing endpoint consistency for pagination patterns
- Adding sort_by/order_by capabilities to existing endpoints
- Implementing cursor-based pagination for large datasets (complement to offset-based)
Core conventions
- Pagination styles: Two common patterns emerge—(a)
page(1-indexed) +page_sizewithtotal_pagesin response; (b)limit+offset(0-indexed) withhas_nextboolean. Pattern (a) is friendlier for UI pagination controls; pattern (b) is more SQL-native. Choose one per service; mixing within a service confuses clients.page_sizeorlimitshould have age=1, le=<MAX>constraint (common max: 100 or 1000).
- Offset calculation: When using
page/page_size, calculateoffset = (page - 1) * page_sizein the route handler or service layer before passing to repository. When usinglimit/offset, pass directly. Both approaches translate toLIMIT {limit} OFFSET {offset}in SQL.
- Response pagination metadata: Standardize on a
PaginationInfoor inline fields embedded in the data response. Common fields:page(current page, 1-indexed),page_sizeorlimit(records per page),totalortotal_records(total count across all pages),total_pages(ceiling division:(total + page_size - 1) // page_size),has_next(boolean:(offset + limit) < totalorpage < total_pages), optionalhas_prev(boolean:page > 1oroffset > 0). Return metadata alongsidedatalist in the response envelope.
- Multi-value filters via FastAPI `Query`: For filters that accept multiple values (e.g.,
status,store_ids,segment_codes), useOptional[List[str]] = Query(None, description="..."). The client sends?status=pending&status=approvedor?status[]=pending&status[]=approved(FastAPI accepts both). In the query builder, translate to SQLINclause orANY(ARRAY[...]).
- Comma-separated multi-value filters: Some endpoints accept comma-separated values in a single param (e.g.,
?items=ITEM-001,ITEM-002,ITEM-003). UseOptional[str] = Query(None)and split by comma in the service or repository layer before building SQL. This pattern is common for legacy APIs or when the client cannot send array query params.
- Hierarchical filters: Product or location hierarchies (e.g., segment → family → class → brick; zone → format → state → region → city → store) use separate query params for each level. Each is optional; when provided, it narrows results to that level. Example:
?segment=BEVERAGES&family=SOFT_DRINKS&class=COLA. Query builder appliesWHEREclauses for each non-null filter. Some services support both singular and plural param names (?store=...and?stores=...); prefer plural for multi-value, singular for single value.
- Sorting via `sort_by` + `sort_order` or `order_by` + `direction`: Two naming conventions—
sort_by(field name) +sort_order(asc/desc) ororder_by+direction. Choose one per service. Use FastAPIQuerywithregex="^(ASC|DESC)$"orregex="^(asc|desc)$"for order validation. Map user-facing sort field names (e.g.,doh,stock,sales) to actual column names in query builder via asort_mappingdict. Default sort is usuallycreated_at DESCor a domain-specific default (e.g.,total_actual_qty DESCfor forecast data).
- QueryBuilder pattern: Encapsulate SQL construction in a
QueryBuilderclass. It receives filters, pagination params, and sort params; returns(query, params)tuple with parameterized placeholders ($1, $2, ...for PostgreSQL,?for others). The builder resets params per query via_reset_params()and adds params via_add_param(value)returning a placeholder. Separate methods for data query (build_data_query) and count query (build_count_query) sharing the same filter logic.
- Repository layer pagination: The repository fetches two results in parallel—
(records_data, total_count)—viaasyncio.gatheror sequential calls. It executes the count query to gettotal_count, then executes the data query withLIMIT/OFFSET. Service layer constructs the response object with data + pagination metadata. For download endpoints (no pagination), omitLIMIT/OFFSETfrom the query.
- Search across multiple fields: A single
searchquery param applies a case-insensitive substring match across multiple columns. In SQL, useWHERE (LOWER(field1) LIKE LOWER(:search) OR LOWER(field2) LIKE LOWER(:search) OR ...)with param%{search}%. Some implementations useILIKE(PostgreSQL) or full-text search. Common searchable fields: item codes, descriptions, store IDs, order IDs.
- Pydantic models for query params: Define a
QueryParamsPydantic model (e.g.,InventoryQueryParams,ForecastQuery) to encapsulate all filters, pagination, sorting, and search params. This separates route handler param extraction from business logic. The model can provide helper methods like@property def limit(self)to derive limit frompage_sizeor computeoffsetfrompageandpage_size.
- FastAPI route handler: Extract query params via
Query()for primitive types or depend on Pydantic model. Calculateoffset = (page - 1) * page_sizeif needed. Call service layer withquery_paramsobject or individual params. Return response viaResponseData.ok(data=..., pagination=...)or a typed response model wrapping data + metadata.
- Default and max constraints: Pagination params should have defaults and constraints:
page: int = Query(1, ge=1),page_size: int = Query(20, ge=1, le=100),limit: int = Query(20, ge=1, le=1000),offset: int = Query(0, ge=0). Document max values in endpoint docstring. Constants likeDEFAULT_PAGE_SIZE = 20,MAX_PAGE_SIZE = 1000centralize these values.
- RBAC / hierarchy access control: Some endpoints filter results by user's hierarchy access (e.g., user can only see data for their assigned stores or segments). This is modeled as
List[HierarchyFilter]derived from user context (x-user-data JWT). The query builder applies RBAC filters as additionalWHEREclauses (e.g.,WHERE (segment = ANY(:allowed_segments) OR :allowed_segments = '{all}')). Cross-referencepython-dao-and-databasefor DAO-level RLS patterns.
- Caching paginated responses: For expensive queries, cache results by a key derived from
(query_params, hierarchy_filters, org_id, run_id). Serialize the Pydantic response model to JSON for cache storage. Cache TTL is typically 1 hour. Invalidate cache on data writes. Use Redis or in-memory cache. Avoid caching every page individually; instead cache the full result set or the first page and accept cache misses for deeper pages.
- Cursor/keyset pagination — and *why* it beats offset for large or mutating sets: offset pagination (
LIMIT/OFFSET) has two failure modes the conventions above don't fix. Correctness: when rows are inserted or deleted between two page fetches, the offset shifts, so the client silently skips rows or sees the same row twice across page boundaries. Performance: the database must scan and discard alloffsetrows before returning the page, so deep pages (OFFSET 100000) degrade linearly. Cursor (keyset) pagination fixes both by paginating relative to a stable ordering key instead of a numeric skip:WHERE (sort_key, id) > (:last_sort_key, :last_id) ORDER BY sort_key, id LIMIT :n. Return an opaque, encoded `next_cursor` (the last row's ordering key(s) — never a raw offset the client can tamper with) plushas_next. It requires a total, stable sort — append a unique tiebreaker (e.g.id) so ties can't reorder between requests. Trade-off: no "jump to page 50" and no exacttotal_pages. Use offset for small, bounded, human-paged lists; use cursor for infinite scroll, large tables, and any list that mutates under the reader.
The offset-skips-rows / deep-page-cost rationale and the opaque-cursor convention follow common API design canon (e.g. Stripe's list pagination). Stack-agnostic; the(sort_key, id)keyset predicate maps to any ordered store.
Skeleton / example
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 95 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/api-pagination-filtering-sorting/SKILL.md
Popularity
- 7-day trend score
- 5
Not refreshed yet.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/ajyadav013/claude-kit/api-pagination-filtering-sorting)