SKILL.md
REST API with Node.js and Express
Automate the creation of production-ready REST APIs with Node.js, Express, Jest, and Supertest following industry best practices.
Workflow
Follow these steps in order:
1. Create Project Structure
Run the initialization script to set up the project:
bash scripts/init_project.sh <project-name>
This creates the project directory, initializes npm, installs dependencies (express, dotenv, jest, supertest), and configures package.json with test scripts.
2. Design API Specification
Gather requirements from the user and create a structured API specification. Use the format defined in references/api-spec-format.md.
Ask the user:
- What resources does the API manage? (e.g., users, todos, products)
- What operations are needed? (CRUD: Create, Read, Update, Delete)
- What fields does each resource have?
- What validation rules apply? (required fields, data types, constraints)
Create a specification document (JSON or markdown table) that defines:
- Endpoints (path, method)
- Request body schema with validation rules
- Query parameters
- Path parameters
- Expected responses (success and error cases)
Save the specification to <project-name>/api-spec.json or <project-name>/api-spec.md.
3. Generate Project Structure
Create the standard project structure:
cd <project-name>
mkdir -p src/routes src/controllers src/middleware tests
Copy template files:
# Core application files
cp templates/app-template.js src/app.js
cp templates/server-template.js src/server.js
# Middleware
cp templates/error-handler.js src/middleware/errorHandler.js
cp templates/validation-middleware.js src/middleware/validation.js
# Configuration files
cp templates/.env.example .env.example
cp templates/.gitignore .gitignore
Create a .env file from .env.example with default values.
4. Generate Route and Controller Code
For each endpoint in the specification, generate:
Route file (src/routes/<resource>.js):
- Import express and controller
- Define router with HTTP method and path
- Apply validation middleware
- Connect to controller functions
- Export router
Controller file (src/controllers/<resource>Controller.js):
- Import error handling utilities
- Implement business logic for each operation
- Use async/await with proper error handling
- Return appropriate HTTP status codes
- Handle edge cases (not found, validation errors)
Update app.js:
- Import and register route modules
- Mount routes with base path (e.g.,
/api/resource)
Refer to references/best-practices.md for:
- Proper HTTP status codes
- Error handling patterns
- Async/await usage
- Input validation
- Route organization
5. Generate Validation Schemas
For endpoints with request bodies, create validation schemas using the validation middleware:
const createSchema = {
title: {
type: 'string',
required: true,
minLength: 1,
maxLength: 200
},
description: {
type: 'string',
required: false
}
};
Apply validation in routes:
router.post('/', validateBody(createSchema), controller.create);
6. Generate Comprehensive Tests
For each endpoint, generate test files in tests/ directory following the patterns in references/testing-patterns.md.
Create tests for:
Success Cases:
- Valid requests return expected responses
- Correct status codes
- Response body structure matches specification
- Data is properly created/updated/deleted
Failure Cases:
- Missing required fields return 400
- Invalid data types return 400
- Non-existent resources return 404
- Validation errors return appropriate messages
Edge Cases:
- Empty strings in required fields
- Very long inputs (exceeding max length)
- Special characters and potential XSS
- Malformed JSON
- Boundary values (min/max lengths)
- Duplicate resources (if uniqueness required)
- Concurrent requests
Use the test template structure:
const request = require('supertest');
const app = require('../src/app');
describe('Resource API', () => {
describe('GET /api/resource', () => {
// Tests here
});
describe('POST /api/resource', () => {
// Tests here
});
// ... other methods
});
7. Run Tests
Execute the test suite:
cd <project-name>
npm test
Review test results:
- All tests should pass
- If tests fail, debug and fix the implementation
- Ensure test coverage is comprehensive
Run tests in watch mode during development:
npm run test:watch
Project Structure
The generated project follows this structure:
<project-name>/
├── src/
│ ├── app.js # Express app setup with middleware
│ ├── server.js # Server entry point
│ ├── routes/ # Route definitions
│ │ └── <resource>.js
│ ├── controllers/ # Business logic
│ │ └── <resource>Controller.js
│ ├── middleware/ # Custom middleware
│ │ ├── errorHandler.js # Error handling utilities
│ │ └── validation.js # Request validation
│ └── models/ # Data models (optional)
├── tests/ # Test files
│ └── <resource>.test.js
├── .env # Environment variables
├── .env.example # Environment template
├── .gitignore # Git ignore rules
├── package.json # Dependencies and scripts
└── api-spec.json # API specification
Best Practices
Consult these references for detailed guidance:
- API Specification Format:
references/api-spec-format.md - Node.js Best Practices:
references/best-practices.md - Testing Patterns:
rest-api-nodejs/references/testing-patterns.md
Key principles:
- Use appropriate HTTP status codes (200, 201, 204, 400, 404, 500)
- Implement consistent error response format
- Use async/await with proper error handling
- Validate all inputs before processing
- Separate routes from business logic
- Write comprehensive tests (success, failure, edge cases)
- Use environment variables for configuration
- Follow RESTful conventions
Running the API
Start the development server:
npm run dev
Start the production server:
npm start
The API will be available at http://localhost:3000 (or the port specified in .env).
Testing
Run all tests:
npm test
Run tests in watch mode:
npm run test:watch
Next Steps
After generating the API:
- Review generated code for correctness
- Run tests and verify all pass
- Test endpoints manually using tools like curl or Postman
- Add database integration if needed
- Implement authentication/authorization if required
- Add additional middleware (CORS, helmet, rate limiting)
- Deploy to production environment