APIのページネーション、フィルタリング、ソート
大規模なデータセットをページ単位で返し、クライアントが結果をフィルタリングおよびソートできるようにし、一貫したクエリパラメータを公開してSaaS APIをスケールさせます。
「APIのページネーション、フィルタリング、ソート」はCoddyKit上の無料AI Powered SaaS: Stripe + Auth + Billing + Deployレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはAI Powered SaaS: Stripe + Auth + Billing + Deploy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 AI Powered SaaS: Stripe + Auth + Billing + Deployコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
Why Not Return Everything?
An endpoint that returns 50,000 rows is slow, heavy, and crashes clients. Pagination returns data in manageable chunks, while filtering and sorting let clients ask for exactly what they need.
Offset Pagination
The simplest approach uses page and limit. You skip (page - 1) * limit rows and take limit rows.
GET /api/users?page=2&limit=20Implementing Offset in Prisma
Prisma exposes skip and take for offset pagination.
const users = await prisma.user.findMany({
skip: (page - 1) * limit,
take: limit
});Returning Metadata
Clients need to know how many pages exist. Return the data plus a total count and computed page info.
const total = await prisma.user.count();
return Response.json({
data: users,
page,
totalPages: Math.ceil(total / limit)
});The Offset Problem
Large offsets are slow because the database still scans skipped rows, and inserts can shift items between pages. For big or live datasets, prefer cursor pagination.
Cursor Pagination
A cursor points to the last item seen. The next request fetches rows after that cursor — fast and stable even as data changes.
const users = await prisma.user.findMany({
take: limit,
skip: 1,
cursor: { id: lastId },
orderBy: { id: 'asc' }
});Filtering by Query Params
Read filter params from the URL and build a where clause. Use contains for search-style filters.
const q = searchParams.get('search');
const where = q ? { name: { contains: q, mode: 'insensitive' } } : {};Combining Multiple Filters
Build the where object conditionally so only provided params apply. Prisma combines them with AND by default.
const where = {};
if (status) where.status = status;
if (minPrice) where.price = { gte: Number(minPrice) };Sorting Safely
Accept a sort field and direction, but whitelist allowed fields so clients cannot order by arbitrary or sensitive columns.
const allowed = ['name', 'createdAt', 'price'];
const field = allowed.includes(sort) ? sort : 'createdAt';
const orderBy = { [field]: dir === 'desc' ? 'desc' : 'asc' };Validating Query Params
Coerce and clamp inputs: cap limit so a client cannot request a million rows, and default page to 1.
const limit = Math.min(Number(searchParams.get('limit')) || 20, 100);
const page = Math.max(Number(searchParams.get('page')) || 1, 1);Best Practices
Design scalable list endpoints:
- Always paginate large collections
- Use cursor pagination for big or live data
- Return metadata (total, pages)
- Whitelist sort fields and clamp limits
Quick Check
Test your pagination knowledge.
Recap
You learned to build scalable list APIs:
- Paginate with
skip/takeor cursors - Return total and page metadata
- Build dynamic
whereclauses for filtering - Whitelist sort fields and clamp the limit
Your API now handles large datasets efficiently.
よくある質問
「APIのページネーション、フィルタリング、ソート」レッスンは無料ですか?
はい。「APIのページネーション、フィルタリング、ソート」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、AI Powered SaaS: Stripe + Auth + Billing + Deployコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 AI Powered SaaS: Stripe + Auth + Billing + Deployコースには全4レッスンが含まれています。
「APIのページネーション、フィルタリング、ソート」で何を学びますか?
大規模なデータセットをページ単位で返し、クライアントが結果をフィルタリングおよびソートできるようにし、一貫したクエリパラメータを公開してSaaS APIをスケールさせます。 ブラウザで直接実行するハンズオンコードでAI Powered SaaS: Stripe + Auth + Billing + Deployを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
AI Powered SaaS: Stripe + Auth + Billing + Deployを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのAI Powered SaaS: Stripe + Auth + Billing + Deployは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。
「APIのページネーション、フィルタリング、ソート」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このAI Powered SaaS: Stripe + Auth + Billing + Deployレッスンでコードを書いて実行できますか?
はい。すべてのAI Powered SaaS: Stripe + Auth + Billing + Deployレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- RESTful API設計の原則
- データベーススキーマとORM
- 最初のAPIエンドポイント
- APIのページネーション、フィルタリング、ソート