Guía para principiantes: API REST con Node.js y Express

Aprende a crear una API REST con Node.js y Express: CRUD, pruebas con Postman o curl y pautas para APIs seguras y escalables.

31 ago 2025 • 4 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Las APIs impulsan la mayoría de las aplicaciones que usamos a diario, desde redes sociales hasta apps del clima. Una API REST Representational State Transfer es una forma común y sencilla de permitir que aplicaciones se comuniquen entre sí. En esta guía práctica te acompaño paso a paso para crear una API REST con Node.js y Express, ideal para quienes comienzan y para equipos que buscan construir aplicaciones a medida y software a medida de forma rápida y escalable.

Lo que aprenderás

- Qué es una API REST

- Cómo preparar Node.js y Express

- Cómo crear rutas para operaciones CRUD Crear, Leer, Actualizar, Eliminar

- Cómo probar tu API con herramientas como Postman o curl

Paso 1 Inicializa tu proyecto

Crea una carpeta de proyecto y arranca npm:

mkdir rest-api-demo

cd rest-api-demo

npm init -y

Instala Express:

npm install express

Paso 2 Crea el servidor

Crea un archivo llamado server.js y define un servidor básico con Express:

const express = require(`express`);

const app = express();

const PORT = 3000;

app.use(express.json());

app.listen(PORT, () => { console.log(`Servidor ejecutándose en https://localhost:${PORT}`); });

Ejecuta tu servidor

node server.js

Deberías ver en la consola

Servidor ejecutándose en https://localhost:3000

Paso 3 Crea rutas CRUD

Construyamos una API sencilla para gestionar una lista de libros:

let books = [

{ id: 1, title: `Atomic Habits`, author: `James Clear` },

{ id: 2, title: `The Pragmatic Programmer`, author: `Andrew Hunt` }

];

// Obtener todos los libros

app.get(`/books`, (req, res) => { res.json(books); });

// Obtener un libro por ID

app.get(`/books/:id`, (req, res) => { const book = books.find(b => b.id === parseInt(req.params.id)); if (book) { res.json(book); } else { res.status(404).json({ message: `Libro no encontrado` }); } });

// Agregar un nuevo libro

app.post(`/books`, (req, res) => { const newBook = { id: books.length + 1, title: req.body.title, author: req.body.author }; books.push(newBook); res.status(201).json(newBook); });

// Actualizar un libro existente

app.put(`/books/:id`, (req, res) => { const book = books.find(b => b.id === parseInt(req.params.id)); if (!book) return res.status(404).json({ message: `Libro no encontrado` }); book.title = req.body.title; book.author = req.body.author; res.json(book); });

// Eliminar un libro

app.delete(`/books/:id`, (req, res) => { books = books.filter(b => b.id !== parseInt(req.params.id)); res.json({ message: `Libro eliminado` }); });

Paso 4 Prueba tu API

Usa Postman o curl para verificar los endpoints:

GET /books Obtener todos los libros

GET /books/1 Obtener el libro con ID 1

POST /books con cuerpo JSON Agregar un nuevo libro

PUT /books/1 con cuerpo JSON Actualizar el libro con ID 1

DELETE /books/1 Eliminar el libro con ID 1

Paso 5 Próximos pasos

Ya creaste tu primera API REST con Node.js y Express. El siguiente paso natural es conectar una base de datos como MongoDB o PostgreSQL, añadir autenticación con JWT u OAuth, implementar validaciones y desplegar en la nube para escalar. Si tu empresa necesita acelerar este proceso con aplicaciones a medida y software a medida, en Q2BSTUDIO te ayudamos de extremo a extremo con arquitectura, desarrollo, pruebas, despliegue y observabilidad.

Por qué Q2BSTUDIO

- Experiencia en construcción de APIs seguras y escalables

- Especialistas en inteligencia artificial, ia para empresas y agentes IA para automatizar procesos y mejorar la toma de decisiones

- Enfoque integral en ciberseguridad incluyendo prácticas de hardening y pentesting

- Servicios cloud aws y azure para despliegues resilientes y de alto rendimiento

- Servicios inteligencia de negocio y analítica con power bi para transformar datos en decisiones

Si buscas un partner para crear tu plataforma o modernizar sistemas legados, explora nuestro desarrollo de aplicaciones a medida y software a medida. Y cuando llegue el momento de llevar tu API a producción con alta disponibilidad, nuestros servicios cloud aws y azure te permiten automatizar despliegues, observabilidad y escalado bajo demanda.

Consejos extra

- Versiona tu API v1 v2 con prefijos de ruta

- Añade middlewares de validación con librerías como joi o zod

- Centraliza el manejo de errores y logs

- Documenta con OpenAPI Swagger para facilitar el consumo

- Protege con rate limiting, CORS y autenticación

Con estos fundamentos podrás construir APIs que sirvan como columna vertebral de productos digitales, integraciones B2B y soluciones de automatización que aprovechen inteligencia artificial, ciberseguridad de primer nivel y analítica avanzada con power bi, impulsando el crecimiento sostenible de tu negocio.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat