Node.js logoNode.js INTERMEDIATE

Express.js REST API

Complete guide to building REST APIs with Express.js including routing, middleware, database integration, error handling, and testing

18 min read
expressnodejsrest-apimiddlewareroutingdatabasemongodbsqlerror-handlingtestingauthentication

Express.js Basic Setup

Initialize Express server and configure essential middleware

Express Server Setup

Create and configure a basic Express server with essential middleware

javascript
🟢 Essential - Every Express app starts with this setup
💡 Use dotenv for environment variables in production
⚡ Enable cors() for cross-origin requests from frontend
📌 Body parsers (json/urlencoded) required for POST requests
🔗 Related: helmet for security headers, compression for gzip

Middleware Functions

Create custom middleware for authentication, logging, and request processing

javascript
🟢 Essential - Middleware is the heart of Express
💡 Order matters - middleware runs in sequence
⚠️ Don't forget next() or response will hang
📌 app.use() applies to all routes, router.use() to specific routes
⚡ Keep middleware focused on single responsibility

Routing & REST APIs

Define routes and implement RESTful API endpoints

CRUD Operations

Implement Create, Read, Update, Delete operations following REST conventions

javascript
🟢 Essential - Standard REST API operations
💡 Use proper HTTP methods: GET (read), POST (create), PUT/PATCH (update), DELETE
📌 Return appropriate status codes: 200 OK, 201 Created, 404 Not Found
⚡ Use async/await for cleaner asynchronous code
⚠️ Always validate and sanitize user input
🔗 Related: express-validator for input validation

Router Organization

Organize routes into modular routers for scalable API structure

javascript
💡 Separate routes by resource or feature for maintainability
📌 Use router.route() to chain methods for same path
⚡ Mount routers with prefixes: app.use('/api/users', userRouter)
🟢 Essential for large applications - keeps code organized
🔗 Related: express.Router() for creating modular routes

Database Integration

Connect and interact with databases in Express

MongoDB with Mongoose

Connect Express to MongoDB using Mongoose ODM for data modeling

javascript
🟢 Essential for MongoDB - Mongoose simplifies database operations
💡 Define schemas for data validation and structure
⚡ Use connection pooling for better performance
📌 Handle connection errors and implement retry logic
⚠️ Never expose database credentials in code
🔗 Related: MongoDB Atlas for cloud hosting

SQL Database Integration

Connect Express to PostgreSQL/MySQL using query builders or ORMs

javascript
💡 Use Prisma or Sequelize for type-safe database access
📌 Knex.js for flexible SQL query building
⚡ Use prepared statements to prevent SQL injection
⚠️ Always use parameterized queries, never concatenate SQL
🟢 Essential - Choose ORM based on project needs
🔗 Related: pg for PostgreSQL, mysql2 for MySQL

Error Handling & Testing

Handle errors gracefully and test your API endpoints

Error Handling Best Practices

Implement centralized error handling and custom error responses

javascript
🟢 Essential - Proper error handling improves user experience
💡 Use error middleware (4 parameters) for centralized handling
📌 Create custom error classes for different error types
⚠️ Never expose stack traces in production
⚡ Log errors but send user-friendly messages to client
🔗 Related: winston or pino for logging

Testing Express APIs

Write unit and integration tests for API endpoints

javascript
🟢 Essential - Tests ensure API reliability
💡 Use Jest + Supertest for API testing
📌 Test both success and error scenarios
⚡ Mock external dependencies for unit tests
🎯 Aim for 80%+ code coverage
🔗 Related: Postman for manual API testing