0Pricing
AI Powered SaaS: Stripe + Auth + Billing + Deploy · Lección

Paginación, filtrado y ordenación de API

Haga que su API de SaaS escale devolviendo grandes conjuntos de datos por páginas, permitiendo a los clientes filtrar y ordenar resultados y exponiendo parámetros de consulta coherentes.

Paginación, filtrado y ordenación de API es una lección gratuita de AI Powered SaaS: Stripe + Auth + Billing + Deploy en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de AI Powered SaaS: Stripe + Auth + Billing + Deploy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de AI Powered SaaS: Stripe + Auth + Billing + Deploy incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

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.

Preguntas frecuentes

¿La lección «Paginación, filtrado y ordenación de API» es gratis?

Sí — el texto completo de «Paginación, filtrado y ordenación de API» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de AI Powered SaaS: Stripe + Auth + Billing + Deploy, actualiza a CoddyKit PRO. El curso de AI Powered SaaS: Stripe + Auth + Billing + Deploy incluye 4 lecciones en total.

¿Qué aprenderé en «Paginación, filtrado y ordenación de API»?

Haga que su API de SaaS escale devolviendo grandes conjuntos de datos por páginas, permitiendo a los clientes filtrar y ordenar resultados y exponiendo parámetros de consulta coherentes. Practicas AI Powered SaaS: Stripe + Auth + Billing + Deploy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar AI Powered SaaS: Stripe + Auth + Billing + Deploy?

No se requiere experiencia previa. AI Powered SaaS: Stripe + Auth + Billing + Deploy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Paginación, filtrado y ordenación de API»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de AI Powered SaaS: Stripe + Auth + Billing + Deploy?

Sí. Cada lección de AI Powered SaaS: Stripe + Auth + Billing + Deploy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Principios del diseño de API RESTful
  2. Esquema de base de datos y ORM
  3. Primeros endpoints de la API
  4. Paginación, filtrado y ordenación de API
← Volver a AI Powered SaaS: Stripe + Auth + Billing + Deploy