Build production-ready RESTful APIs with Express.js including routing, middleware, validation, and error handling for scalable backend services
Build production-ready RESTful APIs with Express.js including routing, middleware, validation, and error handling for scalable backend services
/plugin marketplace add pluginagentmarketplace/custom-plugin-nodejs/plugin install nodejs-developer-plugin@pluginagentmarketplace-nodejsThis skill inherits all available tools. When active, it can use any tool Claude has access to.
assets/config.yamlreferences/GUIDE.mdscripts/helper.pyMaster building robust, scalable REST APIs with Express.js, the de-facto standard for Node.js web frameworks.
Build a basic Express API in 5 steps:
npm install expressconst express = require('express');
const app = express();
// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Routes
app.use('/api/users', userRoutes);
app.use('/api/products', productRoutes);
// Error handling
app.use(errorHandler);
app.listen(3000, () => console.log('Server running'));
// GET /api/users - Get all users
// GET /api/users/:id - Get user by ID
// POST /api/users - Create user
// PUT /api/users/:id - Update user
// DELETE /api/users/:id - Delete user
const router = express.Router();
router.get('/', getAllUsers);
router.get('/:id', getUserById);
router.post('/', createUser);
router.put('/:id', updateUser);
router.delete('/:id', deleteUser);
module.exports = router;
// Authentication middleware
const authenticate = (req, res, next) => {
const token = req.headers.authorization;
if (!token) return res.status(401).json({ error: 'Unauthorized' });
// Verify token...
next();
};
// Validation middleware
const validate = (schema) => (req, res, next) => {
const { error } = schema.validate(req.body);
if (error) return res.status(400).json({ error: error.message });
next();
};
// Usage
router.post('/users', authenticate, validate(userSchema), createUser);
// Custom error class
class APIError extends Error {
constructor(message, statusCode) {
super(message);
this.statusCode = statusCode;
}
}
// Global error handler
app.use((err, req, res, next) => {
const statusCode = err.statusCode || 500;
res.status(statusCode).json({
success: false,
error: err.message,
...(process.env.NODE_ENV === 'development' && { stack: err.stack })
});
});
/api/v1/, /api/v2/){
"dependencies": {
"express": "^4.18.0",
"helmet": "^7.0.0", // Security headers
"cors": "^2.8.5", // Cross-origin requests
"morgan": "^1.10.0", // HTTP logger
"express-validator": "^7.0.0", // Input validation
"express-rate-limit": "^6.0.0" // Rate limiting
}
}
// Success
{ success: true, data: {...} }
// Error
{ success: false, error: "Message" }
// Pagination
{
success: true,
data: [...],
pagination: { page: 1, limit: 10, total: 100 }
}
200 OK - Successful GET/PUT201 Created - Successful POST204 No Content - Successful DELETE400 Bad Request - Validation error401 Unauthorized - Auth required403 Forbidden - No permission404 Not Found - Resource not found500 Internal Error - Server errorsrc/
├── controllers/ # Route handlers
├── routes/ # Route definitions
├── middlewares/ # Custom middleware
├── models/ # Data models
├── services/ # Business logic
├── utils/ # Helpers
└── app.js # Express setup
Complete user API:
const express = require('express');
const router = express.Router();
const { body } = require('express-validator');
// GET /api/users
router.get('/', async (req, res, next) => {
try {
const { page = 1, limit = 10 } = req.query;
const users = await User.find()
.limit(limit)
.skip((page - 1) * limit);
res.json({ success: true, data: users });
} catch (error) {
next(error);
}
});
// POST /api/users
router.post('/',
body('email').isEmail(),
body('password').isLength({ min: 8 }),
async (req, res, next) => {
try {
const user = await User.create(req.body);
res.status(201).json({ success: true, data: user });
} catch (error) {
next(error);
}
}
);
module.exports = router;
Use Express REST API when:
This skill should be used when the user asks to "create a slash command", "add a command", "write a custom command", "define command arguments", "use command frontmatter", "organize commands", "create command with file references", "interactive command", "use AskUserQuestion in command", or needs guidance on slash command structure, YAML frontmatter fields, dynamic arguments, bash execution in commands, user interaction patterns, or command development best practices for Claude Code.
This skill should be used when the user asks to "create an agent", "add an agent", "write a subagent", "agent frontmatter", "when to use description", "agent examples", "agent tools", "agent colors", "autonomous agent", or needs guidance on agent structure, system prompts, triggering conditions, or agent development best practices for Claude Code plugins.
This skill should be used when the user asks to "create a hook", "add a PreToolUse/PostToolUse/Stop hook", "validate tool use", "implement prompt-based hooks", "use ${CLAUDE_PLUGIN_ROOT}", "set up event-driven automation", "block dangerous commands", or mentions hook events (PreToolUse, PostToolUse, Stop, SubagentStop, SessionStart, SessionEnd, UserPromptSubmit, PreCompact, Notification). Provides comprehensive guidance for creating and implementing Claude Code plugin hooks with focus on advanced prompt-based hooks API.