react-java-interview-prep/nodejs-api at main · beckham617/react-java-interview-prep · GitHub
Skip to content

Latest commit

 

History

History

Folders and files

README.md

Node.js Express RESTful API

A sample Node.js Express application demonstrating RESTful API design with proper project structure, controllers, services, and models.

🚀 Features

  • RESTful API Design - Follows REST principles
  • Modular Architecture - Controllers, Services, Models separation
  • Input Validation - Request validation middleware
  • Error Handling - Comprehensive error handling
  • Security - Helmet for security headers
  • Logging - Morgan for HTTP request logging
  • CORS Support - Cross-origin resource sharing enabled

📁 Project Structure

nodejs-api/
├── src/
│   ├── controllers/          # Request handlers
│   │   ├── userController.js
│   │   └── productController.js
│   ├── services/            # Business logic
│   │   ├── userService.js
│   │   └── productService.js
│   ├── models/              # Data models
│   │   ├── User.js
│   │   └── Product.js
│   ├── routes/              # API routes
│   │   ├── userRoutes.js
│   │   └── productRoutes.js
│   ├── middleware/          # Custom middleware
│   │   └── validation.js
│   └── server.js            # Main server file
├── package.json
└── README.md

🛠️ Installation

  1. Clone or navigate to the project directory

    cd nodejs-api
  2. Install dependencies

    npm install
  3. Start the server

    # Development mode (with auto-restart)
    npm run dev
    
    # Production mode
    npm start

📡 API Endpoints

Health Check

  • GET /health - Server health status

Users API

  • GET /api/users - Get all users
    • Query params: search, role
  • GET /api/users/:id - Get user by ID
  • POST /api/users - Create new user
  • PUT /api/users/:id - Update user
  • DELETE /api/users/:id - Delete user

Products API

  • GET /api/products - Get all products
    • Query params: search, category, inStock, minPrice, maxPrice
  • GET /api/products/:id - Get product by ID
  • POST /api/products - Create new product
  • PUT /api/products/:id - Update product
  • DELETE /api/products/:id - Delete product
  • PATCH /api/products/:id/stock - Update product stock

📝 API Examples

Create a User

curl -X POST http://localhost:3000/api/users \
  -H "Content-Type: application/json" \
  -d '{
    "name": "John Doe",
    "email": "john@example.com",
    "age": 30,
    "role": "user"
  }'

Create a Product

curl -X POST http://localhost:3000/api/products \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Laptop",
    "description": "High-performance laptop",
    "price": 999.99,
    "category": "Electronics",
    "stock": 10
  }'

Search Products

curl "http://localhost:3000/api/products?search=laptop&inStock=true"

Update Product Stock

curl -X PATCH http://localhost:3000/api/products/1/stock \
  -H "Content-Type: application/json" \
  -d '{"quantity": -2}'

🔧 Configuration

The server runs on port 3000 by default. You can change this by setting the PORT environment variable:

PORT=8080 npm start

🏗️ Architecture

Controllers

  • Handle HTTP requests and responses
  • Validate input data
  • Call appropriate services
  • Return formatted responses

Services

  • Contain business logic
  • Handle data operations
  • Perform validations
  • Manage data state

Models

  • Define data structure
  • Provide data manipulation methods
  • Handle data validation
  • Convert to/from JSON

Routes

  • Define API endpoints
  • Map URLs to controllers
  • Apply middleware
  • Handle route parameters

🛡️ Security Features

  • Helmet - Sets security headers
  • CORS - Configurable cross-origin requests
  • Input Validation - Request data validation
  • Error Handling - Secure error responses

📊 Sample Data

The application comes with sample data:

Users

  • John Doe (admin)
  • Jane Smith (user)
  • Bob Johnson (user)

Products

  • Laptop (Electronics)
  • Smartphone (Electronics)
  • Coffee Mug (Accessories)
  • Wireless Headphones (Electronics)
  • Desk Lamp (Furniture)

🚀 Getting Started

  1. Start the server: npm run dev
  2. Visit: http://localhost:3000/health
  3. Test the APIs using the examples above
  4. Explore the code structure to understand the patterns

📚 Learning Points

This project demonstrates:

  • RESTful API design
  • MVC architecture pattern
  • Separation of concerns
  • Error handling strategies
  • Input validation
  • Express.js best practices
  • Node.js project structure