AI Powered SaaS: Stripe + Auth + Billing + Deploy · Lezione

Paginazione, filtraggio e ordinamento delle API

Renda scalabile la Sua API SaaS restituendo i dataset di grandi dimensioni in pagine, consentendo ai client di filtrare e ordinare i risultati ed esponendo parametri di query coerenti.

Lezione 4 di 413 passaggi

Paginazione, filtraggio e ordinamento delle API è una lezione AI Powered SaaS: Stripe + Auth + Billing + Deploy gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento AI Powered SaaS: Stripe + Auth + Billing + Deploy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso AI Powered SaaS: Stripe + Auth + Billing + Deploy include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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=20

Implementing 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/take or cursors
  • Return total and page metadata
  • Build dynamic where clauses for filtering
  • Whitelist sort fields and clamp the limit

Your API now handles large datasets efficiently.

Gratis per iniziare

Impara AI Powered SaaS: Stripe + Auth + Billing + Deploy con un tutor IA — gratis

Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.

Corsi
12
Lezioni
48

Domande Frequenti

La lezione «Paginazione, filtraggio e ordinamento delle API» è gratuita?

Sì — il testo completo di «Paginazione, filtraggio e ordinamento delle API» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso AI Powered SaaS: Stripe + Auth + Billing + Deploy, passa a CoddyKit PRO. Il corso AI Powered SaaS: Stripe + Auth + Billing + Deploy include 4 lezioni in totale.

Cosa imparerò in «Paginazione, filtraggio e ordinamento delle API»?

Renda scalabile la Sua API SaaS restituendo i dataset di grandi dimensioni in pagine, consentendo ai client di filtrare e ordinare i risultati ed esponendo parametri di query coerenti. Eserciti AI Powered SaaS: Stripe + Auth + Billing + Deploy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare AI Powered SaaS: Stripe + Auth + Billing + Deploy?

Non è richiesta alcuna esperienza precedente. AI Powered SaaS: Stripe + Auth + Billing + Deploy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Paginazione, filtraggio e ordinamento delle API»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione AI Powered SaaS: Stripe + Auth + Billing + Deploy?

Sì. Ogni lezione AI Powered SaaS: Stripe + Auth + Billing + Deploy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Principi di progettazione delle API RESTful
  2. Schema del database e ORM
  3. Primi endpoint API
  4. Paginazione, filtraggio e ordinamento delle API
← Torna a AI Powered SaaS: Stripe + Auth + Billing + Deploy