Skip to content

Shanto1459/Running-Web-API

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

TCSS-460 HelloWorld API

University of Washington Tacoma

School of Engineering and Technology

Computer Science and Systems

TCSS 460 A - Client/Server Programming for Internet Applications

Autumn 2025

Instructor: Professor Charles Bryan

Email: cfb3@uw.edu


🎯 Complete Beginner? Start Here!

Never used Node.js or built an API before? Follow these 4 steps:

Step 1: Install Node.js

  • Download and install from nodejs.org (version 18 or higher)
  • Verify installation: Open terminal and run node --version

Step 2: Run These Commands

cd TCSS-460-helloworld-api
npm install
cp .env.example .env
npm run dev

You should see:

πŸš€ HelloWorld API server running on port 8000
πŸ“š Environment: development
πŸ”— Health check: http://localhost:8000/health

Step 3: Test Your API

Step 4: Next Steps

  1. Read JSON Fundamentals - Understand the data format APIs use
  2. Read HTTP Fundamentals - Learn how web APIs work
  3. Try other endpoints in Swagger UI
  4. Read Development Workflow - Understand what just happened

Having trouble? Check the Troubleshooting Guide


πŸ“š Course Project Overview

This project serves as the foundational template for TCSS-460: Client/Server Programming for Internet Applications. It demonstrates modern Express.js and TypeScript development patterns, providing students with a professional-grade starting point for learning web API development.

What You'll Learn

  • 🌐 HTTP Protocol Fundamentals - Request/Response model, methods, status codes
  • πŸš€ Express.js Architecture - Middleware patterns, routing, MVC design
  • πŸ“˜ TypeScript Development - Type safety, modern JavaScript features
  • πŸ”§ API Design Patterns - RESTful principles, error handling, validation
  • πŸ§ͺ Testing Strategies - Automated testing with Postman/Newman
  • πŸ›‘οΈ Security Practices - CORS, input sanitization, error handling
  • πŸ“¦ Professional Workflow - Git, linting, formatting, deployment

Key Features

  • βœ… Modern TypeScript - Strict type safety with path mapping
  • βœ… Express.js Best Practices - Professional middleware architecture
  • βœ… HTTP Method Demonstrations - GET, POST, PUT, PATCH, DELETE
  • βœ… Parameter Handling - Query, path, body, and header parameters
  • βœ… Health Monitoring - Basic and detailed health check endpoints
  • βœ… Error Handling - Comprehensive error management system
  • βœ… CORS Configuration - Production-ready cross-origin setup
  • βœ… Request Logging - Development and production logging
  • βœ… Environment Configuration - Type-safe environment management
  • βœ… API Testing - Complete Postman collection with automated tests
  • βœ… Educational Documentation - 13 comprehensive guides covering HTTP, Express, TypeScript, and more
  • βœ… Interactive API Documentation - Swagger UI for hands-on testing

πŸš€ Quick Start

Prerequisites

Required:

  • Node.js 18.0.0 or higher (Download)
  • npm 8.0.0 or higher (comes with Node.js)
  • Code Editor with TypeScript support (VS Code recommended)

Optional:

Verify Prerequisites:

node --version   # Should show v18.0.0 or higher
npm --version    # Should show 8.0.0 or higher

Installation

1. Clone or Download the Project

# If using Git
git clone <repository-url>
cd TCSS-460-helloworld-api

# Or download ZIP and extract to your preferred location

2. Install Dependencies

npm install

This will install all required packages including Express, TypeScript, and development tools.

3. Environment Setup

# Copy the example environment file
cp .env.example .env

# The default configuration works for local development
# You can edit .env if you need to change the port or other settings

4. Start Development Server

npm run dev

You should see:

πŸš€ HelloWorld API server running on port 8000
πŸ“š Environment: development
πŸ”— Health check: http://localhost:8000/health
πŸ“– Documentation: http://localhost:8000/docs

Verification

Test the API is working:

Option 1: Browser

Option 2: cURL (Command Line)

curl http://localhost:8000/health

Option 3: Interactive Documentation

Expected Response:

{
  "success": true,
  "data": {
    "status": "OK",
    "timestamp": "2025-09-30T10:30:00.000Z"
  },
  "message": "API is healthy",
  "timestamp": "2025-09-30T10:30:00.000Z"
}

βœ… If you see this response, your API is running correctly!


πŸƒ How to Run the Project

Development Mode (Recommended for Active Development)

npm run dev
  • Starts server with automatic restart on file changes
  • Runs on port 8000 (or PORT from .env)
  • Hot-reload enabled (no manual restart needed)
  • Detailed logging enabled
  • TypeScript compilation on-the-fly

When to use: Daily development, making changes, learning

Production Build

# Step 1: Compile TypeScript to JavaScript
npm run build

# Step 2: Start the production server
npm start
  • Compiles TypeScript β†’ JavaScript in dist/ folder
  • Runs optimized production code
  • Minimal logging
  • No hot-reload (manual restart required)

When to use: Testing production build, deployment preparation

Type Checking (No Execution)

npm run type-check
  • Checks TypeScript types without running the server
  • Fast validation of code correctness
  • Useful before committing code

When to use: Before git commits, verifying code correctness

Build with Watch Mode

npm run build:watch
  • Continuously compiles TypeScript as you make changes
  • Useful for debugging compiled JavaScript

When to use: Debugging compilation issues

Quality Assurance

# Check code style and potential errors
npm run lint

# Automatically fix linting issues
npm run lint:fix

# Format code with Prettier
npm run format

# Check if code is properly formatted
npm run format:check

When to use: Before submitting assignments, maintaining code quality

Complete Pre-Commit Check

npm run type-check && npm run lint && npm run format

Run all quality checks at once before committing code.

Testing

# Run Postman collection tests (requires Newman)
npm run test:postman

When to use: Verifying API functionality, automated testing


πŸ“– Documentation Guide

This project includes comprehensive educational documentation to help you understand web API development from the ground up.

Interactive Documentation

Access while server is running:

URL Description
http://localhost:8000/api-docs Swagger UI - Interactive API documentation where you can test endpoints directly in your browser
http://localhost:8000/docs Documentation Viewer - Browse and read all educational guides in rendered markdown
http://localhost:8000/ API Discovery - JSON response listing all available endpoints

Educational Guides (13 Documents)

All guides are located in the docs/ directory and cover everything from HTTP basics to advanced patterns.

HTTP Foundations (5 documents)

Essential understanding of the HTTP protocol:

  1. http-fundamentals.md πŸ“‘

    • HTTP protocol basics and structure
    • Headers, methods, status codes overview
    • Request/response anatomy
    • Start here if new to HTTP
  2. http-history-evolution.md πŸ“œ

    • Evolution from HTTP/0.9 to HTTP/3
    • Why protocols changed over time
    • Modern HTTP/2 and HTTP/3 features
  3. http-methods.md πŸ”§

    • Deep dive into GET, POST, PUT, PATCH, DELETE
    • When to use each method
    • Idempotency and safety concepts
    • Real-world examples
  4. http-status-codes.md 🎯

    • Complete guide to HTTP status codes (1xx-5xx)
    • What each code means
    • When to use which code
    • Client vs server errors
  5. request-response-model.md πŸ”„

    • Detailed HTTP request/response cycle
    • Headers, bodies, and metadata
    • How data flows in web APIs

Architecture & Design (4 documents)

Building well-structured applications:

  1. client-server-architecture.md πŸ—οΈ

    • Client-server model fundamentals
    • Separation of concerns
    • API architectural patterns
  2. node-express-architecture.md βš™οΈ

    • Express.js MVC patterns
    • Middleware pipeline explained
    • Routing architecture
    • Essential for understanding this project's structure
  3. typescript-patterns.md πŸ“˜

    • TypeScript best practices for APIs
    • Type definitions and interfaces
    • Generic types and utility types
    • Path mapping and module organization
  4. error-handling-patterns.md 🚨

    • Robust error management strategies
    • Operational vs programming errors
    • Error response standardization
    • Global error handlers

Development & Operations (3 documents)

Professional development practices:

  1. environment-configuration.md πŸ”§

    • Environment setup and management
    • Configuration best practices
    • Development vs production settings
    • Deployment considerations
  2. testing-strategies.md πŸ§ͺ

    • API testing methodologies
    • Unit, integration, and E2E testing
    • Postman collection usage
    • Automated testing with Newman
  3. API_DOCUMENTATION.md πŸ“‹

    • API reference and usage guide
    • Endpoint specifications
    • Request/response examples
  4. README.md (docs folder) πŸ“š

    • Overview of documentation structure
    • Learning path recommendations

Recommended Learning Path

For Complete Beginners:

  1. Start with http-fundamentals.md - Understand the basics
  2. Read request-response-model.md - How APIs communicate
  3. Study http-methods.md - The building blocks
  4. Review http-status-codes.md - API responses
  5. Explore node-express-architecture.md - This project's structure
  6. Practice with interactive Swagger UI
  7. Dive into other topics as needed

For Students with HTTP Knowledge:

  1. node-express-architecture.md - Express patterns
  2. typescript-patterns.md - TypeScript in APIs
  3. error-handling-patterns.md - Professional error handling
  4. testing-strategies.md - Quality assurance
  5. Experiment with the API endpoints

For Advanced Students:

  • All documents are reference materials
  • Focus on environment-configuration.md for deployment
  • Study error handling and testing patterns
  • Extend the API with new features

πŸ“ Project Structure

TCSS-460-helloworld-api/
β”‚
β”œβ”€β”€ src/                                # Source code (TypeScript)
β”‚   β”‚
β”‚   β”œβ”€β”€ index.ts                        # Application entry point
β”‚   β”‚                                   # - Server startup and lifecycle management
β”‚   β”‚                                   # - Graceful shutdown handlers
β”‚   β”‚                                   # - Process error handlers
β”‚   β”‚
β”‚   β”œβ”€β”€ app.ts                          # Express application factory
β”‚   β”‚                                   # - Middleware stack configuration
β”‚   β”‚                                   # - Route registration
β”‚   β”‚                                   # - CORS and security setup
β”‚   β”‚
β”‚   β”œβ”€β”€ types/                          # TypeScript type definitions (3 files)
β”‚   β”‚   β”œβ”€β”€ index.ts                   # Barrel exports for clean imports
β”‚   β”‚   β”œβ”€β”€ apiTypes.ts                # API response interfaces
β”‚   β”‚   └── errorTypes.ts              # Error handling types
β”‚   β”‚
β”‚   β”œβ”€β”€ core/                           # Core infrastructure
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ config/                    # Configuration (1 file)
β”‚   β”‚   β”‚   └── swagger.ts             # OpenAPI/Swagger documentation setup
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ middleware/                # Express middleware (4 files)
β”‚   β”‚   β”‚   β”œβ”€β”€ cors.ts                # CORS policy configuration
β”‚   β”‚   β”‚   β”œβ”€β”€ errorHandler.ts        # Global error handling
β”‚   β”‚   β”‚   β”œβ”€β”€ logger.ts              # Request/response logging
β”‚   β”‚   β”‚   └── validation.ts          # Input validation patterns
β”‚   β”‚   β”‚
β”‚   β”‚   └── utilities/                 # Helper functions (4 files)
β”‚   β”‚       β”œβ”€β”€ envConfig.ts           # Environment variable management
β”‚   β”‚       β”œβ”€β”€ markdownUtils.ts       # Markdown rendering for docs
β”‚   β”‚       β”œβ”€β”€ responseUtils.ts       # Standardized API responses
β”‚   β”‚       └── validationUtils.ts     # Input sanitization utilities
β”‚   β”‚
β”‚   β”œβ”€β”€ controllers/                   # Request handlers (4 files)
β”‚   β”‚   β”œβ”€β”€ index.ts                   # Barrel exports
β”‚   β”‚   β”œβ”€β”€ healthController.ts        # Health monitoring endpoints
β”‚   β”‚   β”œβ”€β”€ helloController.ts         # HTTP methods demonstration
β”‚   β”‚   └── parametersController.ts    # Parameter types demonstration
β”‚   β”‚
β”‚   └── routes/                        # Route definitions
β”‚       β”œβ”€β”€ index.ts                   # Main router configuration
β”‚       └── open/                      # Public routes (no authentication)
β”‚           β”œβ”€β”€ index.ts               # Route aggregation
β”‚           β”œβ”€β”€ docsRoutes.ts          # Documentation viewer endpoints
β”‚           β”œβ”€β”€ healthRoutes.ts        # Health check routes
β”‚           β”œβ”€β”€ helloRoutes.ts         # Hello World demo routes
β”‚           └── parametersRoutes.ts    # Parameter demo routes
β”‚
β”œβ”€β”€ docs/                              # Educational documentation (13 files)
β”‚   β”œβ”€β”€ http-fundamentals.md          # HTTP protocol basics
β”‚   β”œβ”€β”€ http-history-evolution.md     # HTTP version history
β”‚   β”œβ”€β”€ http-methods.md               # HTTP methods deep dive
β”‚   β”œβ”€β”€ http-status-codes.md          # Status codes reference
β”‚   β”œβ”€β”€ request-response-model.md     # Request/response cycle
β”‚   β”œβ”€β”€ client-server-architecture.md # Architectural patterns
β”‚   β”œβ”€β”€ node-express-architecture.md  # Express.js patterns
β”‚   β”œβ”€β”€ typescript-patterns.md        # TypeScript best practices
β”‚   β”œβ”€β”€ error-handling-patterns.md    # Error management
β”‚   β”œβ”€β”€ environment-configuration.md  # Environment setup
β”‚   β”œβ”€β”€ testing-strategies.md         # Testing approaches
β”‚   β”œβ”€β”€ API_DOCUMENTATION.md          # API reference
β”‚   β”œβ”€β”€ README.md                     # Documentation index
β”‚   └── openapi.json                  # OpenAPI specification
β”‚
β”œβ”€β”€ testing/                          # Test suites
β”‚   └── postman/                      # Postman collection
β”‚       β”œβ”€β”€ HelloWorld-API.postman_collection.json
β”‚       β”œβ”€β”€ HelloWorld-Environment.postman_environment.json
β”‚       └── README.md                 # Testing guide
β”‚
β”œβ”€β”€ ai/                               # AI assistant instructions
β”‚   └── instructions.md               # Development guidelines for AI
β”‚
β”œβ”€β”€ dist/                             # Compiled JavaScript (generated by build)
β”œβ”€β”€ node_modules/                     # Dependencies (generated by npm install)
β”‚
β”œβ”€β”€ .env.example                      # Environment variables template
β”œβ”€β”€ .eslintrc.js                      # ESLint configuration
β”œβ”€β”€ .gitignore                        # Git ignore rules
β”œβ”€β”€ package.json                      # Project metadata & scripts
β”œβ”€β”€ package-lock.json                 # Locked dependency versions
β”œβ”€β”€ tsconfig.json                     # TypeScript configuration
└── README.md                         # This file

What Goes Where?

Adding a new endpoint?

  1. Create controller in src/controllers/
  2. Create routes in src/routes/open/
  3. Register routes in src/routes/index.ts

Adding types?

  • Add to src/types/apiTypes.ts or src/types/errorTypes.ts
  • Export from src/types/index.ts

Adding middleware?

  • Create in src/core/middleware/
  • Register in src/app.ts

Adding utilities?

  • Create in src/core/utilities/
  • Use throughout your controllers

Adding documentation?

  • Add markdown files to docs/
  • Link from docs/README.md

πŸ“‘ API Endpoints

Health Monitoring

Basic Health Check

GET /health

# Example:
curl http://localhost:8000/health

# Response:
{
  "success": true,
  "data": {
    "status": "OK",
    "timestamp": "2025-09-30T10:30:00.000Z"
  },
  "message": "API is healthy",
  "timestamp": "2025-09-30T10:30:00.000Z"
}

Detailed Health Check

GET /health/detailed

# Example:
curl http://localhost:8000/health/detailed

# Response:
{
  "success": true,
  "data": {
    "status": "OK",
    "timestamp": "2025-09-30T10:30:00.000Z",
    "details": {
      "uptime": 123456,
      "memory": {
        "used": 45678912,
        "total": 67891234
      },
      "version": "1.0.0",
      "environment": "development"
    }
  },
  "message": "Detailed health information",
  "timestamp": "2025-09-30T10:30:00.000Z"
}

HTTP Methods Demonstration

All five major HTTP methods demonstrated on the same endpoint:

GET - Retrieve Data

GET /hello

curl http://localhost:8000/hello

# Response:
{
  "success": true,
  "data": {
    "message": "Hello, World!",
    "method": "GET",
    "description": "GET is used for retrieving data. It's safe and idempotent.",
    "timestamp": "2025-09-30T10:30:00.000Z"
  },
  "message": "Hello message retrieved successfully",
  "timestamp": "2025-09-30T10:30:00.000Z"
}

POST - Create Data

POST /hello

curl -X POST http://localhost:8000/hello

# Response: (Status 201 Created)
{
  "success": true,
  "data": {
    "message": "Hello, World!",
    "method": "POST",
    "description": "POST is used for creating resources or submitting data.",
    "timestamp": "2025-09-30T10:30:00.000Z"
  },
  "message": "Hello message created successfully",
  "timestamp": "2025-09-30T10:30:00.000Z"
}

PUT - Replace Data

PUT /hello

curl -X PUT http://localhost:8000/hello

PATCH - Update Data

PATCH /hello

curl -X PATCH http://localhost:8000/hello

DELETE - Remove Data

DELETE /hello

curl -X DELETE http://localhost:8000/hello

Parameters Demonstration

Query Parameters

GET /parameters/query?name=John

# Example:
curl "http://localhost:8000/parameters/query?name=John"

# Response:
{
  "success": true,
  "data": {
    "message": "Hello, John!",
    "parameterType": "query",
    "parameterValue": "John",
    "validation": {
      "applied": ["required", "length(1-50)", "sanitized"],
      "sanitized": false
    },
    "description": "Query parameters are ideal for optional filters, pagination...",
    "timestamp": "2025-09-30T10:30:00.000Z"
  },
  "message": "Query parameter processed successfully",
  "timestamp": "2025-09-30T10:30:00.000Z"
}

Path Parameters

GET /parameters/path/{name}

# Example:
curl http://localhost:8000/parameters/path/Alice

# Response:
{
  "success": true,
  "data": {
    "message": "Hello, Alice!",
    "parameterType": "path",
    "parameterValue": "Alice",
    "validation": {
      "applied": ["required", "length(1-30)", "alphanumeric", "sanitized"],
      "sanitized": false
    },
    "description": "Path parameters identify specific resources...",
    "timestamp": "2025-09-30T10:30:00.000Z"
  }
}

Request Body Parameters

POST /parameters/body
Content-Type: application/json

# Example:
curl -X POST http://localhost:8000/parameters/body \
  -H "Content-Type: application/json" \
  -d '{"name":"Bob"}'

# Response:
{
  "success": true,
  "data": {
    "message": "Hello, Bob!",
    "parameterType": "body",
    "parameterValue": "Bob",
    "validation": {
      "applied": ["required", "length(1-100)", "json-format", "sanitized"],
      "sanitized": false
    },
    "description": "Request body is ideal for complex data structures...",
    "timestamp": "2025-09-30T10:30:00.000Z"
  }
}

Header Parameters

GET /parameters/headers
X-User-Name: Charlie

# Example:
curl http://localhost:8000/parameters/headers \
  -H "X-User-Name: Charlie"

# Response:
{
  "success": true,
  "data": {
    "message": "Hello, Charlie!",
    "parameterType": "header",
    "parameterValue": "Charlie",
    "validation": {
      "applied": ["required", "length(1-50)", "header-format", "sanitized"],
      "sanitized": false
    },
    "description": "Headers carry metadata about requests...",
    "timestamp": "2025-09-30T10:30:00.000Z"
  }
}

Documentation Endpoints

API Discovery

GET /

curl http://localhost:8000/

# Returns: JSON with all available endpoints and their descriptions

Documentation Viewer

GET /docs

# Opens: Interactive documentation browser

GET /docs/{filename}

# Example:
curl http://localhost:8000/docs/http-methods.md
# Returns: Rendered markdown documentation

Swagger UI

GET /api-docs

# Opens: Interactive Swagger UI for testing all endpoints

Response Structure

All successful responses follow this format:

{
  "success": true,
  "data": { /* endpoint-specific data */ },
  "message": "Optional success message",
  "timestamp": "2025-09-30T10:30:00.000Z"
}

All error responses follow this format:

{
  "success": false,
  "message": "Human-readable error description",
  "code": "ERROR_CODE",
  "timestamp": "2025-09-30T10:30:00.000Z",
  "details": { /* optional error details (development only) */ }
}

πŸ› οΈ Development Workflow

Recommended IDE Setup (VS Code)

Essential Extensions:

  • ESLint - Real-time linting and error detection
  • Prettier - Code formatter - Automatic code formatting
  • TypeScript Importer - Auto-import TypeScript types
  • REST Client - Test APIs without leaving VS Code
  • Thunder Client - Alternative to Postman (lightweight)

Install all at once:

code --install-extension dbaeumer.vscode-eslint
code --install-extension esbenp.prettier-vscode
code --install-extension pmneo.tsimporter
code --install-extension humao.rest-client
code --install-extension rangav.vscode-thunder-client

Daily Development Workflow

1. Start Your Day

# Pull latest changes (if using Git)
git pull

# Install any new dependencies
npm install

# Start development server
npm run dev

2. Make Changes

  • Edit TypeScript files in src/
  • Server automatically restarts on file save
  • Check terminal for compilation errors
  • Test endpoints in browser or Postman

3. Test Your Changes

# Check TypeScript types
npm run type-check

# Run linter
npm run lint

# Format code
npm run format

# Test endpoints
curl http://localhost:8000/your-endpoint

4. Before Committing (Git)

# Run all quality checks
npm run type-check && npm run lint && npm run format

# Build to verify production compilation
npm run build

# Commit your changes
git add .
git commit -m "Descriptive commit message"
git push

Debugging Tips

TypeScript Errors:

  • Run npm run type-check to see all type errors
  • Check tsconfig.json for configuration
  • Ensure imports use correct path aliases (@/, @middleware/*)

Server Won't Start:

  • Check if port 8000 is in use: lsof -i :8000 (Mac/Linux)
  • Change PORT in .env file
  • Verify Node.js version: node --version

Module Not Found:

  • Run npm install to install dependencies
  • Clear node_modules and reinstall: rm -rf node_modules && npm install

CORS Errors:

  • Check CORS_ORIGINS in .env
  • Add your frontend URL to allowed origins
  • Review src/core/middleware/cors.ts

πŸ”§ Configuration

Environment Variables

The .env file controls server behavior. Copy from .env.example to get started.

Available Configuration:

# Server Configuration
PORT=8000                              # Port number for the API server
NODE_ENV=development                   # Environment: development | staging | production

# CORS Configuration
CORS_ORIGINS=http://localhost:3000,http://localhost:8000
# Comma-separated list of allowed origins for cross-origin requests

# Request Configuration
BODY_LIMIT=10mb                        # Maximum request body size
ENABLE_LOGGING=true                    # Enable/disable request logging

# API Configuration
API_VERSION=1.0.0                      # Current API version (shown in health checks)

Environment-Specific Settings:

Development (default):

NODE_ENV=development
ENABLE_LOGGING=true
BODY_LIMIT=10mb
  • Verbose logging with request/response details
  • Detailed error messages with stack traces
  • Hot-reload enabled
  • CORS allows localhost origins

Production:

NODE_ENV=production
ENABLE_LOGGING=false
BODY_LIMIT=1mb
CORS_ORIGINS=https://yourdomain.com
  • Minimal logging (errors only)
  • Generic error messages (no stack traces)
  • Optimized performance
  • Strict CORS policy

TypeScript Configuration

The project uses strict TypeScript for maximum type safety:

Key Features:

  • Path Mapping - Clean imports with @/ aliases
  • Strict Type Checking - All strict options enabled
  • ES2022 Target - Modern JavaScript features
  • Source Maps - Debug compiled JavaScript

Import Examples:

// Clean imports using path aliases
import { ApiResponse, ErrorCodes } from '@/types';
import { sendSuccess } from '@utilities/responseUtils';
import { getHealth } from '@controllers/healthController';
import { corsMiddleware } from '@middleware/cors';

// Instead of messy relative imports like:
// import { ApiResponse } from '../../../types';

πŸ§ͺ Testing

Testing with Postman

Complete API test collection included in testing/postman/

Setup:

  1. Install Postman (if not already installed)

  2. Import Collection

    • Open Postman
    • Click Import button
    • Select testing/postman/HelloWorld-API.postman_collection.json
  3. Import Environment

    • Click Import button again
    • Select testing/postman/HelloWorld-Environment.postman_environment.json
    • Select "HelloWorld-Environment" from environment dropdown
  4. Run Tests

    • Click Run Collection to run all tests
    • Or click individual requests to test one at a time

Test Categories:

βœ… Health Checks

  • Basic health endpoint validation
  • Detailed health response structure
  • Response time verification

βœ… HTTP Methods

  • GET, POST, PUT, PATCH, DELETE demonstrations
  • Response format validation
  • Status code verification

βœ… Parameters

  • Query parameter handling
  • Path parameter extraction
  • Request body parsing
  • Header parameter reading

βœ… Error Handling

  • 404 Not Found responses
  • Invalid request handling
  • Malformed JSON detection

βœ… CORS Testing

  • Cross-origin request validation
  • Preflight request handling

βœ… Performance

  • Response time benchmarks
  • Response size validation

Automated Testing with Newman

Newman is the command-line collection runner for Postman.

Install Newman:

npm install -g newman

Run Tests:

# Run all tests in collection
npm run test:postman

# Or run manually:
newman run testing/postman/HelloWorld-API.postman_collection.json \
  -e testing/postman/HelloWorld-Environment.postman_environment.json

CI/CD Integration:

  • Newman can be integrated into GitHub Actions, GitLab CI, etc.
  • Automated testing on every commit
  • See testing/postman/README.md for details

Testing in Browser

Simple endpoint testing:

  1. Start the server: npm run dev

  2. Open browser and navigate to:

  3. For POST/PUT/PATCH/DELETE, use Swagger UI or Postman

Testing with cURL

Command-line testing examples:

# GET request
curl http://localhost:8000/health

# POST request with JSON body
curl -X POST http://localhost:8000/parameters/body \
  -H "Content-Type: application/json" \
  -d '{"name":"Test"}'

# Request with custom header
curl http://localhost:8000/parameters/headers \
  -H "X-User-Name: TestUser"

# Verbose output (see full request/response)
curl -v http://localhost:8000/health

🚨 Troubleshooting

Common Issues and Solutions

Issue: Port 8000 already in use

Error: listen EADDRINUSE: address already in use :::8000

Solutions:

# Option 1: Find and kill the process using port 8000
# macOS/Linux:
lsof -ti :8000 | xargs kill -9

# Windows:
netstat -ano | findstr :8000
taskkill /PID <PID> /F

# Option 2: Change the port in .env
# Edit .env and change PORT=8000 to PORT=3000 (or any available port)

Issue: Module not found errors

Error: Cannot find module 'express'

Solution:

# Reinstall dependencies
npm install

# If that doesn't work, clean install:
rm -rf node_modules package-lock.json
npm install

Issue: TypeScript compilation errors

Error: Cannot find name 'Request'

Solution:

# Run type check to see all errors
npm run type-check

# Ensure @types packages are installed
npm install --save-dev @types/node @types/express

# Check tsconfig.json is present and valid

Issue: CORS errors in browser

Access to fetch at 'http://localhost:8000' has been blocked by CORS policy

Solution:

# Add your frontend URL to .env
CORS_ORIGINS=http://localhost:3000,http://localhost:8000

# Restart server after changing .env

Issue: Changes not reflecting Solution:

# Make sure you're running in dev mode (auto-restart)
npm run dev

# If in production mode, rebuild:
npm run build && npm start

# Clear browser cache (Cmd+Shift+R or Ctrl+Shift+R)

Issue: JSON syntax errors

SyntaxError: Unexpected token in JSON at position X

Solution:

  • Validate JSON using jsonlint.com
  • Check for trailing commas, missing quotes
  • Ensure Content-Type header is application/json

Issue: npm install fails Solution:

# Clear npm cache
npm cache clean --force

# Update npm
npm install -g npm@latest

# Try again
npm install

Getting Help

  1. Check Documentation

    • Read relevant docs in docs/ folder
    • Check Swagger UI at /api-docs
  2. Check Logs

    • Terminal output shows detailed error messages
    • Look for stack traces in development mode
  3. Ask Professor Bryan

    • Office hours
    • Email: cfb3@uw.edu
    • Canvas discussion forum
  4. Online Resources


πŸ›‘οΈ Security Considerations

This project includes basic security practices appropriate for learning:

Implemented Security Features

1. CORS (Cross-Origin Resource Sharing)

  • Configurable allowed origins in .env
  • Prevents unauthorized frontend access
  • Located in src/core/middleware/cors.ts

2. Input Validation & Sanitization

  • All user inputs are sanitized
  • Length validation on strings
  • Type checking on parameters
  • See src/core/utilities/validationUtils.ts

3. Error Handling

  • Prevents information leakage
  • Generic error messages in production
  • Detailed errors only in development
  • See src/core/middleware/errorHandler.ts

4. Environment Variable Protection

  • .env file not committed to Git
  • Sensitive configuration kept separate
  • .env.example template provided

5. Request Size Limits

  • Body size limited to prevent abuse
  • Configurable via BODY_LIMIT in .env

Security Best Practices for Students

DO:

  • βœ… Validate all user inputs
  • βœ… Sanitize data before processing
  • βœ… Use environment variables for config
  • βœ… Keep dependencies updated
  • βœ… Use HTTPS in production

DON'T:

  • ❌ Commit .env files
  • ❌ Store passwords in code
  • ❌ Trust user input without validation
  • ❌ Expose detailed errors in production
  • ❌ Ignore security warnings

Future Security Enhancements

As you advance in the course, you may add:

  • Authentication (JWT, OAuth)
  • Rate limiting
  • Request throttling
  • SQL injection prevention (when adding database)
  • XSS protection
  • CSRF tokens

πŸ“š Additional Resources

Official Documentation

Core Technologies:

HTTP & REST:

Tools:

Recommended Books

For Beginners:

  • "Node.js Design Patterns" by Mario Casciaro
  • "Learning TypeScript" by Josh Goldberg
  • "REST API Design Rulebook" by Mark Masse

For Advanced Students:

  • "Web Scalability for Startup Engineers" by Artur Ejsmont
  • "Building Microservices" by Sam Newman

Online Courses & Tutorials

Free Resources:

Video Tutorials:

UW Tacoma Resources

Course Materials:

  • Canvas course page for TCSS-460
  • Office hours schedule
  • Assignment submission guidelines

Support:

  • SET Computer Labs
  • UW Tacoma Library computing resources
  • Student Tech Support

πŸŽ“ Academic Integrity

Collaboration Policy

Allowed:

  • βœ… Discussing concepts and approaches with classmates
  • βœ… Helping others debug general issues
  • βœ… Sharing knowledge about tools and documentation
  • βœ… Using official documentation and course materials
  • βœ… Asking questions in office hours

Not Allowed:

  • ❌ Copying code from other students
  • ❌ Sharing assignment solutions
  • ❌ Using code from previous quarters without permission
  • ❌ Submitting AI-generated code without understanding it
  • ❌ Having someone else write your code

Using This Template

This HelloWorld API template is:

  • βœ… Provided for learning - Study, understand, and modify
  • βœ… Assignment starter - Use as foundation for assignments
  • βœ… Final project base - Extend for your project

When using this template:

  • Understand every line - Don't just copy and paste
  • Cite when appropriate - Acknowledge template origins in assignments
  • Add your own work - Extend with original features
  • Follow assignment guidelines - Some assignments may restrict template use

Citation Format

If required to cite this template:

Based on TCSS-460 HelloWorld API Template
University of Washington Tacoma, Autumn 2025
Professor Charles Bryan

Questions About Academic Integrity?

Contact:


🀝 Contributing

For Students: Improving the Template

Found a bug? Have a suggestion? Contributions are welcome!

Before Contributing:

  1. Check if issue already exists
  2. Discuss with Professor Bryan
  3. Follow project code style

How to Contribute:

  1. Report Issues

    • Describe the problem clearly
    • Include steps to reproduce
    • Share error messages
  2. Suggest Improvements

    • Explain the benefit
    • Provide examples
    • Consider backward compatibility
  3. Submit Code Changes

    # Create a new branch
    git checkout -b feature/your-improvement
    
    # Make your changes
    # Test thoroughly
    
    # Commit with clear message
    git commit -m "Add: feature description"
    
    # Push and create pull request
    git push origin feature/your-improvement

Code Style Guidelines

TypeScript:

  • Use full variable names (request not req)
  • Prefer functional expressions when readable
  • Add JSDoc comments for functions
  • Use interfaces for complex types

Structure:

  • Controllers handle business logic
  • Routes define endpoints
  • Middleware processes requests
  • Utilities provide helpers

Documentation:

  • Update README for new features
  • Add inline comments for complex logic
  • Create docs for major concepts

Review Process

  1. Code submitted for review
  2. Professor Bryan or TA reviews
  3. Feedback provided
  4. Changes made if needed
  5. Merged when approved

πŸ“„ License

MIT License - This project is free to use for educational purposes.


πŸ“ž Contact & Support

Course Instructor

Professor Charles Bryan

  • Email: cfb3@uw.edu
  • Office Hours: (Posted on Canvas)
  • Course: TCSS 460 A - Client/Server Programming for Internet Applications
  • Quarter: Autumn 2025

Institution

University of Washington Tacoma School of Engineering and Technology Computer Science and Systems Division

Campus Address: 1900 Commerce Street Tacoma, WA 98402-3100

Getting Help

For Course-Related Questions:

  1. Check this README and documentation in docs/
  2. Search Canvas discussion forum
  3. Attend office hours
  4. Email Professor Bryan

For Technical Issues:

  1. Check Troubleshooting section above
  2. Review official documentation
  3. Post on Canvas discussion (help others too!)
  4. Email with specific error details

For Assignment Questions:

  • Refer to assignment instructions on Canvas
  • Clarify requirements in office hours
  • Don't wait until the last minute!

🎯 Learning Objectives Recap

By working with this project, you will learn:

HTTP Fundamentals

  • Request/Response model
  • HTTP methods (GET, POST, PUT, PATCH, DELETE)
  • Status codes and their meanings
  • Headers and how to use them

Express.js & Node.js

  • MVC architecture pattern
  • Middleware pipeline
  • Routing and controllers
  • Error handling strategies

TypeScript

  • Type safety in APIs
  • Interfaces and types
  • Modern JavaScript (ES2022)
  • Path mapping and modules

Professional Practices

  • Code organization and structure
  • Environment configuration
  • Testing methodologies
  • Documentation standards
  • Version control with Git

API Design

  • RESTful principles
  • Response standardization
  • Error handling patterns
  • Security considerations

Development Workflow

  • Linting and formatting
  • Type checking
  • Automated testing
  • Deployment preparation

πŸš€ Next Steps

Now that your environment is set up:

  1. βœ… Explore the API

  2. πŸ“– Read the Documentation

    • Start with docs/http-fundamentals.md
    • Follow the recommended learning path
    • Take notes on key concepts
  3. πŸ”§ Experiment

    • Modify existing endpoints
    • Add console.log to understand flow
    • Break things and fix them (learning!)
  4. πŸ§ͺ Test Your Understanding

    • Run Postman collection
    • Try cURL commands
    • Predict responses before making requests
  5. πŸ’‘ Build Something

    • Add a new endpoint
    • Implement new features
    • Apply concepts to assignments
  6. πŸ€” Ask Questions

    • No question is too small
    • Attend office hours
    • Engage with classmates

Ready to build amazing web APIs? Let's get started! πŸŽ“


Built with ❀️ for TCSS-460 students at UW Tacoma

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published