express-rest-api
Build production-ready RESTful APIs with Express.js including routing, middleware, validation, and error handling for scalable backend services
What this skill does
# Express REST API Skill
Master building robust, scalable REST APIs with Express.js, the de-facto standard for Node.js web frameworks.
## Quick Start
Build a basic Express API in 5 steps:
1. **Setup Express** - `npm install express`
2. **Create Routes** - Define GET, POST, PUT, DELETE endpoints
3. **Add Middleware** - JSON parsing, CORS, security headers
4. **Handle Errors** - Centralized error handling
5. **Test & Deploy** - Use Postman/Insomnia, deploy to cloud
## Core Concepts
### 1. Express Application Structure
```javascript
const 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'));
```
### 2. RESTful Route Design
```javascript
// 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;
```
### 3. Middleware Patterns
```javascript
// 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);
```
### 4. Error Handling
```javascript
// 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 })
});
});
```
## Learning Path
### Beginner (2-3 weeks)
- ✅ Setup Express and create basic routes
- ✅ Understand middleware concept
- ✅ Implement CRUD operations
- ✅ Test with Postman
### Intermediate (4-6 weeks)
- ✅ Implement authentication (JWT)
- ✅ Add input validation
- ✅ Organize code (MVC pattern)
- ✅ Connect to database
### Advanced (8-10 weeks)
- ✅ API versioning (`/api/v1/`, `/api/v2/`)
- ✅ Rate limiting and security
- ✅ Pagination and filtering
- ✅ API documentation (Swagger)
- ✅ Performance optimization
## Essential Packages
```javascript
{
"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
}
}
```
## Common Patterns
### Response Format
```javascript
// Success
{ success: true, data: {...} }
// Error
{ success: false, error: "Message" }
// Pagination
{
success: true,
data: [...],
pagination: { page: 1, limit: 10, total: 100 }
}
```
### HTTP Status Codes
- `200 OK` - Successful GET/PUT
- `201 Created` - Successful POST
- `204 No Content` - Successful DELETE
- `400 Bad Request` - Validation error
- `401 Unauthorized` - Auth required
- `403 Forbidden` - No permission
- `404 Not Found` - Resource not found
- `500 Internal Error` - Server error
## Project Structure
```
src/
├── controllers/ # Route handlers
├── routes/ # Route definitions
├── middlewares/ # Custom middleware
├── models/ # Data models
├── services/ # Business logic
├── utils/ # Helpers
└── app.js # Express setup
```
## Production Checklist
- ✅ Environment variables (.env)
- ✅ Security headers (Helmet)
- ✅ CORS configuration
- ✅ Rate limiting
- ✅ Input validation
- ✅ Error handling
- ✅ Logging (Morgan/Winston)
- ✅ Testing (Jest/Supertest)
- ✅ API documentation
## Real-World Example
Complete user API:
```javascript
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;
```
## When to Use
Use Express REST API when:
- Building backend for web/mobile apps
- Creating microservices
- Developing API-first applications
- Need flexible, lightweight framework
- Want large ecosystem and community
## Related Skills
- Async Programming (handle async operations)
- Database Integration (connect to MongoDB/PostgreSQL)
- JWT Authentication (secure your APIs)
- Jest Testing (test your endpoints)
- Docker Deployment (containerize your API)
## Resources
- [Express.js Official Docs](https://expressjs.com)
- [REST API Best Practices](https://restfulapi.net)
- [MDN HTTP Guide](https://developer.mozilla.org/en-US/docs/Web/HTTP)
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.