📱 Applications of Web Programming
🎯 (SE-12-03)
📌 Explore the applications of web programming across a variety of modern contexts.
🖱️ Interactive Websites and Webpages
Interactive websites use client-side JavaScript to respond to user actions in real time — without requiring a full page reload. The Document Object Model (DOM) is the programming interface that allows JavaScript to read and manipulate the structure, style, and content of a live HTML page. Examples include form validation, dropdown navigation, image carousels, and live search filtering. Modern Single Page Applications (SPAs) such as those built with React or Vue extend this further, dynamically rendering entire pages client-side.
🛒 E-Commerce
E-commerce platforms use web programming to support the entire buying lifecycle: product browsing, shopping cart management, payment processing, and order tracking. Key technical requirements include secure HTTPS connections (to protect payment data), session management (to maintain cart state across pages), database integration (to query product catalogues and stock levels), and integration with payment gateway APIs (such as Stripe or PayPal). Examples include Amazon, eBay, and Shopify-powered stores.
📱 Progressive Web Apps (PWAs)
PWAs are web applications built with standard web technologies (HTML, CSS, JavaScript) that offer a native-app-like experience. They are installable on the user's home screen, can work offline via service workers, and receive push notifications. Examples include Twitter Lite, Google Maps, and Starbucks. PWAs are significant because they eliminate the need for a separate iOS/Android codebase while still appearing as a native application to the end-user.
📦 Data Transfer on the Internet
🎯 (SE-12-03)
📌 Investigate and practise how data is transferred across the internet.
📦 Data Packets
When data is sent over the internet, it is broken into small, manageable units called data packets. Each packet contains a header (source IP, destination IP, sequence number, protocol type) and a payload (the actual data fragment). Packets from the same transmission may take different routes through the network and are reassembled in the correct order at the destination. This packet-switching model means the failure of one route does not disrupt the overall transmission — other paths are used instead.
🌐 IP Addresses and IPv4
Every device on a network is assigned an Internet Protocol (IP) address — a unique numerical label used to identify it for communication purposes. IPv4 (Internet Protocol version 4) addresses are 32-bit numbers expressed in dotted-decimal notation, divided into four octets (e.g., 192.168.1.1). IPv4 supports approximately 4.3 billion unique addresses. Due to address exhaustion, Network Address Translation (NAT) is used so that multiple devices on a private network can share a single public IP address. IPv6 was introduced to address this limitation using 128-bit addresses.
🔍 Domain Name System (DNS)
The Domain Name System (DNS) translates human-readable domain names (e.g., www.google.com) into machine-readable IP addresses (e.g., 142.250.70.142). When a user types a URL, the browser queries a DNS resolver (usually provided by their ISP), which traverses a hierarchy of DNS servers (Root → TLD → Authoritative) to resolve the domain. The resolved IP address is then cached locally (for a duration defined by TTL — Time To Live) to speed up future requests.
🌐 Sequence Diagram - DNS Resolution
Understanding hierarchical DNS resolver network
This diagram shows how domain names are translated to IP addresses through a hierarchical DNS resolver network. The user's browser first checks its local cache. If the domain isn't cached, it queries the ISP resolver, which recursively queries the Root Name Server, TLD server, and finally the Authoritative Name Server to obtain the IP address.
Browser participant BC as 🗂️ Browser
Cache participant ISP as 🔍 ISP
Resolver participant Root as 🌍 Root
Name Server participant TLD as 📝 TLD
Server participant Auth as 🔐 Authoritative
NS User->>BC: Type: www.google.com BC-->>BC: Check cache
(TTL valid?) alt Cache Hit BC-->>User: Return IP
(FAST) else Cache Miss BC->>ISP: Query: www.google.com ISP->>Root: Where is .com? Root-->>ISP: Ask TLD server ISP->>TLD: Where is google.com? TLD-->>ISP: Ask Authoritative NS ISP->>Auth: Where is www.google.com? Auth-->>ISP: 142.250.70.142 ISP-->>BC: 142.250.70.142 BC-->>BC: Cache result
(TTL=3600s) BC-->>User: IP Address end User->>User: Browser connects
to 142.250.70.142
Purpose: Trace the DNS resolution process from browser cache check through recursive queries to the authoritative name server
Syllabus Link: SE-12-05
Try This: Use `nslookup` or `dig` command to query DNS servers and observe the resolution path for different domains
📨 Sequence Diagram - HTTP Communication
Client-server request-response cycle
This diagram shows how HTTP requests flow from the browser to the server, trigger database queries, and return responses that the browser renders. It demonstrates both simple data retrieval (GET requests) and form submission with file upload (POST requests), showing how the server processes user interaction and redirects to a success page.
HTML + CSS + JS rect rgb(200, 150, 255) Browser->>Browser: Render HTML
Execute CSS
Load Images end Note over Browser,Server: User Interaction Browser->>Server: POST /submit/assignment
(multipart form data) Server->>Server: Validate input
Process file Server->>DB: INSERT assignment_submission Server-->>Browser: HTTP 302 Redirect
Location: /success Browser->>Server: HTTP GET /success Server-->>Browser: HTTP 200 Success page
Purpose: Understand the HTTP request/response cycle from user action to server processing to browser rendering
Syllabus Link: SE-12-03
Try This: Open browser DevTools (F12), go to Network tab, refresh the page, and watch the actual HTTP requests and responses happen in real-time!
🔌 Web Protocols and Their Ports
🎯 (SE-12-03)
📌 Investigate and describe the function of web protocols and their associated port numbers.
| Protocol | Port(s) | Function |
|---|---|---|
| HTTP | 80 | Hypertext Transfer Protocol — transfers plain-text web content between client and server. Unencrypted; vulnerable to interception. |
| HTTPS | 443 | HTTP Secure — HTTP encrypted with TLS/SSL. Required for any site handling sensitive data (login, payments). Provides confidentiality and integrity. |
| TCP/IP | Various | Transmission Control Protocol / Internet Protocol — the foundational communication suite of the internet. TCP ensures reliable, ordered, error-checked delivery of packets; IP handles addressing and routing. |
| DNS | 53 | Domain Name System — resolves human-readable domain names to IP addresses. Uses UDP for standard queries; TCP for zone transfers. |
| FTP | 21 (control), 20 (data) | File Transfer Protocol — transfers files between a client and server. Unencrypted; largely replaced by SFTP in modern deployments. |
| SFTP | 22 | SSH File Transfer Protocol — secure, encrypted file transfer using SSH. Standard for uploading files to web servers safely. |
| SSL / TLS | 443 | Secure Sockets Layer / Transport Layer Security — cryptographic protocols that provide secure communication over a network. TLS is the modern successor to the deprecated SSL. |
| SMTP | 25, 587 | Simple Mail Transfer Protocol — sends outgoing email from a client to a mail server, or between mail servers. Port 587 is used for authenticated submission. |
| POP3 | 110 | Post Office Protocol 3 — downloads email from a server to a local client, then typically deletes it from the server. Best for single-device access. |
| IMAP | 143 | Internet Message Access Protocol — synchronises email between server and multiple clients without deleting from the server. Best for multi-device access (e.g., phone and laptop). |
🏗️ Diagram - Web Protocol Stack (OSI Layers)
Layered abstraction of network communication
This diagram shows how web protocols are layered, with each layer providing services to the layer above it. HTTP/HTTPS at the application layer relies on TCP for reliable transmission, which relies on IP for routing, which relies on physical layers like Ethernet. Understanding this stack helps explain how the web works from user-facing protocols down to electrical signals.
Port 80/443
Web protocol
What: URLs, requests, responses"] B["📨 TCP
Port varies
Reliable transmission
How: Ordered packets, flow control"] C["📦 IP
Port varies
Routing packets
How: IP addresses, route selection"] D["🔗 Ethernet/WiFi
MAC addresses
Physical transmission
How: Frames, collision detection"] E["⚡ Signals on Wire
Electrons/Light
Physical bits
How: Voltage, frequencies"] A -->|Uses| B B -->|Uses| C C -->|Uses| D D -->|Uses| E style A fill:#E3F2FD,stroke:#1976D2,stroke-width:2px style B fill:#F3E5F5,stroke:#6A1B9A,stroke-width:2px style C fill:#E8F5E9,stroke:#2E7D32,stroke-width:2px style D fill:#FFF3E0,stroke:#E65100,stroke-width:2px style E fill:#FCE4EC,stroke:#C2185B,stroke-width:2px
Purpose: Understand how each protocol layer provides abstraction and services to layers above it
Syllabus Link: SE-12-03
Try This: Trace a single HTTP request down the stack — how many layers does it pass through to reach the wire?
🔐 Processes for Securing the Web
🎯 (SE-12-04, SE-12-07)
📌 Explain the processes and technologies used to secure data and identity on the web.
🏅 SSL/TLS Certificates
An SSL/TLS certificate is a digital document issued by a trusted Certificate Authority (CA) (e.g., Let's Encrypt, DigiCert) that verifies a website's identity and enables encrypted HTTPS connections. When a browser connects to a site, it checks that the certificate is: (1) issued by a trusted CA, (2) not expired, and (3) issued for the correct domain. Without a valid certificate, browsers display a "Not Secure" warning, deterring users and search engines alike.
🔢 Encryption Algorithms
Encryption algorithms transform readable plaintext into unreadable ciphertext, protecting data from interception. Symmetric encryption (e.g., AES-256) uses a single shared key for both encryption and decryption — fast and efficient, but the key must be securely exchanged beforehand. Asymmetric encryption (e.g., RSA-2048) uses a mathematically linked key pair: a public key to encrypt and a private key to decrypt. TLS uses asymmetric encryption to securely exchange a session key, then switches to faster symmetric encryption for the remainder of the connection.
🗝️ Encryption Keys
An encryption key is a string of bits used by an algorithm to encrypt or decrypt data. Public keys are freely shared and used to encrypt data sent to the key's owner. Private keys are kept secret by the owner and used to decrypt data or create digital signatures. Key length determines security strength: a 256-bit AES key has 2256 possible combinations, making brute-force attacks computationally infeasible.
🔑 Authentication and Authorisation
Authentication is the process of verifying who a user is (e.g., verifying a username and password match a database record). Authorisation is the process of verifying what an authenticated user is permitted to do (e.g., checking if a logged-in user has the "admin" role before allowing access to the dashboard). Modern web applications use JSON Web Tokens (JWT) or OAuth 2.0 to manage these processes securely across multiple services.
🔐 Sequence Diagram - Session Management
Stateless authentication with JWT tokens
This diagram shows stateless session management using JWT tokens instead of server-side sessions. On login, the server creates a JWT containing the user's ID and role, signs it cryptographically, and sends it to the browser. For subsequent requests, the browser includes the JWT in the Authorization header. The server verifies the signature and expiration to authenticate the user without accessing the database.
username, password Server->>DB: SELECT user
WHERE username=? DB-->>Server: User record
(with bcrypt hash) Server->>Server: Compare passwords
bcrypt.verify() alt Auth Success Server->>Server: Create JWT
header.payload.signature
include: user_id, role, exp Server-->>Browser: HTTP 200
Set-Cookie: jwt_token else Auth Failed Server-->>Browser: HTTP 401
Unauthorized end Browser->>Browser: Store JWT
in localStorage
or Cookie Note over Browser,Server: Subsequent Requests Browser->>Server: GET /dashboard
Authorization: Bearer JWT Server->>Server: Verify JWT signature
Check expiration
Extract user_id + role alt Token Valid Server->>DB: SELECT user_dashboard
WHERE id = user_id DB-->>Server: Dashboard data Server-->>Browser: HTTP 200
Dashboard HTML else Token Expired or Invalid Server-->>Browser: HTTP 401
Redirect to /login end
Purpose: Trace stateless authentication flow with JWT tokens and password verification
Syllabus Link: SE-12-04, SE-12-07
Try This: Implement JWT-based authentication in a Python Flask or Node.js Express app and trace the token through multiple requests
#️⃣ Hash Values
A hash function is a one-way mathematical function that converts any input into a fixed-length output called a hash value (or digest). For example, the SHA-256 algorithm produces a 64-character hexadecimal hash. Hash functions are deterministic (same input always produces the same hash) but irreversible — it is computationally infeasible to reconstruct the original input from the hash. Web applications use hashing to store passwords securely: the hash of the password is stored, never the password itself. Algorithms like bcrypt add a random salt before hashing to prevent rainbow table attacks.
✍️ Digital Signatures
A digital signature is a cryptographic mechanism that proves the authenticity and integrity of a message or document. The sender hashes the content, then encrypts the hash with their private key to produce the signature. The recipient decrypts the signature using the sender's public key and compares it to their own hash of the received content. If they match, the message has not been tampered with and genuinely originated from the claimed sender. Digital signatures provide non-repudiation — the sender cannot later deny having sent the message.
📊 Big Data and Web Architecture
🎯 (SE-12-03, SE-12-05)
📌 Investigate the effect of big data on web architecture and the ethical considerations of large-scale data collection.
⛏️ Data Mining
Data mining is the process of discovering patterns, correlations, and insights within large datasets using statistical and machine learning techniques. Web platforms mine user interaction data (clicks, search queries, time on page) to personalise recommendations, optimise advertising, and predict future behaviour. For example, Netflix mines viewing history to recommend shows; Google mines search patterns to rank results. Ethical concerns include user consent, data sovereignty, and the potential for discriminatory algorithmic outcomes.
🏷️ Metadata
Metadata is "data about data" — descriptive information that provides context about other data without being the primary content itself. On the web, metadata includes HTTP headers (content type, cache directives), HTML <meta> tags (page description, author, viewport settings), and file metadata (creation date, author, geolocation embedded in photos). Metadata is critical for search engine indexing (SEO), content management, and security analysis. Importantly, metadata can reveal sensitive information even when primary content is private — for example, a photo's EXIF data can expose a user's exact GPS location.
📺 Streaming Service Management
Streaming services (e.g., YouTube, Netflix, Spotify) manage enormous volumes of concurrent data delivery. Key architectural solutions include: Content Delivery Networks (CDNs) — geographically distributed server networks that cache and serve content from the nearest node to reduce latency; Adaptive Bitrate Streaming (ABR) — which dynamically adjusts video quality based on the user's current bandwidth; and load balancers that distribute incoming requests across multiple server instances to prevent any single server from being overwhelmed.
🌍 Role of the W3C
🎯 (SE-12-05)
📌 Investigate and explain the role of the World Wide Web Consortium (W3C) in the development of web applications. The W3C is the international standards body that develops and maintains technical web standards to ensure the web remains open, accessible, and interoperable.
♿ Web Accessibility Initiative (WAI)
Develops the Web Content Accessibility Guidelines (WCAG) — the international standard for making web content accessible to people with disabilities (visual, auditory, cognitive, motor). Compliance levels: A, AA (required by Australian government sites), AAA. Practices include alternative text for images, keyboard-navigable interfaces, and sufficient colour contrast ratios.
🌐 Internationalisation (i18n)
Ensures web technologies support all languages, scripts, and cultures globally. This includes Unicode character encoding (UTF-8), right-to-left (RTL) text support for Arabic/Hebrew, locale-specific date/number formatting, and tools for translating and localising web content without changing the underlying code structure.
🛡️ Web Security
The W3C develops security-related standards such as Content Security Policy (CSP) headers (which restrict the sources from which scripts, styles, and images can be loaded, mitigating XSS attacks), Subresource Integrity (SRI) (verifying third-party CDN resources haven't been tampered with), and the Web Authentication API (WebAuthn) for passwordless login.
🔒 Privacy
The W3C's Privacy Interest Group (PING) reviews all new web specifications for privacy implications. This includes working towards a cookieless web through the Privacy Sandbox initiative, standardising Do Not Track (DNT) headers, and ensuring that new browser APIs cannot be exploited for fingerprinting or tracking users without consent.
🤖 Machine-Readable Data
The W3C develops standards for structured, semantic data that machines (search engines, AI systems) can interpret. This includes Schema.org vocabulary embedded as JSON-LD or microdata in HTML (enabling rich search results), the Resource Description Framework (RDF), and Semantic HTML5 elements (<article>, <nav>, <section>) that provide meaning beyond visual presentation.
🏗️ Modelling a Web Development System
🎯 (SE-12-02, SE-12-06)
📌 Model the elements that form a complete web development system, including the client, server, and database tiers.
📊 Data Flow Diagram - Web System
Understanding DFD notation and multi-tier architecture
This diagram shows how data flows through a web system using DFD notation. External entities (users and APIs) interact with processes (browser, server, authentication service) which access data stores (database). Each arrow shows the type of data flowing between components, demonstrating the separation of concerns and data dependencies in a three-tier architecture.
─────────
External Entity"] Browser(("🌐 Web Browser
─────────
Process")) Server(("🖥️ Web Server
─────────
Process")) Auth(("🔐 Auth Service
─────────
Process")) DB[("💾 Database
─────────
Data Store")] API["📡 External API
─────────
External Entity"] User -->|HTTP Request
User Input| Browser Browser -->|HTTP GET/POST
Form Data| Server Server -->|Verify Credentials| Auth Auth -->|Session Valid| Server Server -->|SQL Query
SELECT/INSERT| DB DB -->|Records
User Data| Server Server -->|API Call
REST Request| API API -->|JSON Response
Data| Server Server -->|HTTP 200
HTML/JSON| Browser Browser -->|Render Page
Display Results| User style User fill:#E3F2FD,stroke:#1976D2,stroke-width:2px style Browser fill:#FFF9C4,stroke:#F57F17,stroke-width:2px style Server fill:#FFE082,stroke:#F57F17,stroke-width:2px style Auth fill:#F8BBD0,stroke:#C2185B,stroke-width:2px style DB fill:#C8E6C9,stroke:#2E7D32,stroke-width:3px style API fill:#FFCCBC,stroke:#E64A19,stroke-width:2px
Purpose: Model data flow through a complete web system with external entities, processes, and data stores
Syllabus Link: SE-12-02
Try This: Create a DFD for an e-commerce system showing order flow from customer → shopping cart → payment processor → inventory database → shipping notification
🎨 Client-Side (Front-End) Web Programming
The client side refers to all code that executes within the user's web browser. Front-end code consists of three complementary technologies: HTML (structure and content), CSS (visual presentation and layout), and JavaScript (interactivity and dynamic behaviour). The browser downloads these files from the server, parses them, and renders the visual page. Client-side code is visible to the user (via browser dev tools) and should never contain sensitive data such as API keys or database credentials.
🖥️ Server-Side (Back-End) Web Programming
The server side refers to code that executes on the web server — invisible to the client. The server receives HTTP requests, applies business logic (authentication, data processing, calculations), queries the database, and returns a response (HTML page or JSON data). Common back-end languages include Python (Django, Flask), JavaScript (Node.js/Express), Ruby (Rails), and PHP. The server environment is protected from end-users and may contain sensitive configuration, credentials, and proprietary algorithms.
💾 Databases — SQL and Non-SQL
🗄️ SQL (Relational) Databases
Store data in structured tables with rows and columns. Relationships between tables are defined by primary and foreign keys. Enforce data integrity via ACID transactions. Examples: PostgreSQL, MySQL, SQLite. Best for: structured, consistent data with complex relationships (e.g., e-commerce orders, user accounts).
📄 Non-SQL (NoSQL) Databases
Store data in flexible formats — documents (JSON), key-value pairs, graphs, or column families. Schema-free, allowing rapid iteration. Examples: MongoDB (documents), Redis (key-value), Neo4j (graphs). Best for: unstructured or evolving data (e.g., social media posts, real-time analytics, content catalogues).
🖥️ Web Browser Influence & Developer Tools
🎯 (SE-12-03, SE-12-06)
📌 Explore and explain how the web browser influences web development decisions, and how developer tools support the build and debug process.
⚙️ Browser Rendering Engines
Different browsers use different rendering engines to parse HTML/CSS and render the visual page: Blink (Chrome, Edge, Opera), WebKit (Safari), and Gecko (Firefox). Differences in engine implementations can cause the same CSS to render slightly differently across browsers — a core challenge of front-end development known as cross-browser compatibility. Developers use tools like Can I Use (caniuse.com) to check which CSS/JavaScript features are supported across browser versions before using them in production.
🛠️ Developer (Dev) Tools
All modern browsers include built-in developer tools (opened with F12 or right-click → Inspect) that allow engineers to inspect, debug, and optimise web applications in real time:
console.log() output for debugging.🎨 Cascading Style Sheets (CSS)
🎯 (SE-12-02, SE-12-06)
📌 Investigate CSS and its impact on the design and maintainability of web applications.
💅 Consistency of Appearance
CSS enables a single stylesheet to control the visual appearance of every page across an entire website. CSS Custom Properties (variables) allow designers to define a value once (e.g., --brand-colour: #6366F1) and reuse it throughout, ensuring colour, typography, and spacing remain consistent. Changing a single variable instantly updates every element that references it. Design systems (such as Google's Material Design or Apple's Human Interface Guidelines) are implemented through CSS to enforce consistent visual language across large products.
/* Define design tokens as CSS variables */
:root {
--primary-colour: #6366F1;
--font-body: 'Inter', sans-serif;
--spacing-md: 1rem;
}
/* Apply consistently across components */
.btn-primary {
background: var(--primary-colour);
font-family: var(--font-body);
padding: var(--spacing-md) calc(var(--spacing-md) * 2);
}
/* Media query for responsive design (flexibility with devices) */
@media (max-width: 768px) {
.grid-3col { grid-template-columns: 1fr; }
}
📱 Flexibility with Browsers and Display Devices
Responsive web design ensures a single codebase adapts to any screen size — from a 27-inch desktop monitor to a 375px mobile screen. CSS media queries apply different styles at defined breakpoints. Flexbox and CSS Grid provide flexible layout systems that redistribute space and reflow content automatically. The viewport meta tag instructs the browser to scale the page to the device's width, preventing the "zoomed-out desktop site" appearance on mobile.
🛠️ CSS Maintenance Tools
🔀 Version Control
🎯 (SE-12-09)
📌 Investigate the reasons for version control and apply it when developing a web application.
🛡️ Why Version Control is Essential
Version control systems (VCS) track every change made to a codebase over time, enabling developers to: roll back to any previous working state if a new change breaks functionality; branch the codebase to develop features or fix bugs in isolation without affecting the main production code; merge contributions from multiple developers working simultaneously; and maintain a complete audit trail of who changed what and why. Git is the dominant distributed VCS; GitHub, GitLab, and Bitbucket are the popular remote hosting platforms.
# Initialise a new repository
git init
# Create a feature branch (isolates work from main)
git checkout -b feature/user-login
# Stage changed files
git add index.html styles.css app.js
# Commit with a descriptive message
git commit -m "Add user login form with client-side validation"
# Push branch to remote repository (GitHub)
git push origin feature/user-login
# Merge feature into main once reviewed
git checkout main
git merge feature/user-login
📦 Code Libraries for Front-End Development
🎯 (SE-12-06)
📌 Explore the types and significance of code libraries available for front-end web development.
⚛️ Frameworks for Complex Web Applications
Front-end frameworks provide a structured architecture for building large, complex web applications. They enforce separation of concerns (UI components, state management, routing) and provide build tools that optimise code for production.
🟨 Template Engines
Template engines allow developers to inject dynamic data into HTML templates on the server before sending the page to the client, avoiding duplicate HTML markup. For example, a product listing page uses a single template and loops through a database result to generate each product card.
{{ }}), control structures ({% %}), and template inheritance.🅱️ Pre-designed CSS Classes
text-lg font-bold text-indigo-600) applied directly in HTML.🔓 Open-Source Software in Web Development
🎯 (SE-12-05)
📌 Explain the use and development of open-source software in relation to web development, including ethical and practical considerations.
The modern web is built almost entirely on open-source software. Web servers (Apache, Nginx), programming languages (Python, Node.js), frameworks (React, Django), and databases (PostgreSQL, MySQL) are all open source. The NPM (Node Package Manager) ecosystem alone hosts over 2 million open-source packages that developers can import with a single command (npm install package-name).
⚖️ Licences and Attribution
Open-source software is governed by licences that define how it may be used, modified, and redistributed. Engineers must understand these before incorporating libraries into commercial projects:
🔐 Security Dependency Risk
Relying on open-source libraries introduces a supply chain security risk: if a maintainer introduces a vulnerability (accidentally or maliciously), all downstream projects that depend on it are affected. Engineers must: regularly run npm audit or equivalent tools to detect known vulnerabilities in dependencies, promptly update packages, and only include libraries with active maintenance and community trust.
⚡ Web Performance & Load Times
🎯 (SE-12-07, SE-12-08)
📌 Investigate methods to support and manage the load times of web pages and applications. Page speed directly impacts user retention — studies show a 1-second delay in load time can reduce conversions by up to 7%.
🗜️ Minification & Compression
Minification removes whitespace, comments, and unused code from HTML/CSS/JS files, reducing file size. GZIP/Brotli compression further compresses files before transmission — the server compresses the file, the browser decompresses it. Typical compression reduces file sizes by 60–80%.
📦 Caching
HTTP Cache-Control headers instruct the browser to store static assets (images, CSS, JS) locally for a defined period. On repeat visits, cached files load instantly without a server request. Service workers in PWAs enable advanced programmatic caching strategies.
🌍 Content Delivery Networks (CDN)
A CDN distributes static assets across servers in multiple geographic locations. Users receive files from the nearest server, dramatically reducing latency. Popular CDNs include Cloudflare, AWS CloudFront, and Fastly.
🖼️ Lazy Loading
Images and heavy components are only loaded when they enter the user's viewport, rather than all at once on page load. Implemented with the loading="lazy" HTML attribute or JavaScript Intersection Observer API. Significantly reduces initial page weight.
✂️ Code Splitting
Bundlers (Webpack, Vite) split a large JavaScript application into smaller chunks that are only loaded when needed. A user visiting the home page doesn't need to download the JavaScript for the account settings page until they navigate there.
📊 Core Web Vitals
Google's set of real-world performance metrics: LCP (Largest Contentful Paint — how fast main content loads), INP (Interaction to Next Paint — responsiveness), and CLS (Cumulative Layout Shift — visual stability). These directly influence Google search ranking.
📝 Web Content Management Systems (CMS)
🎯 (SE-12-06)
📌 Research, experiment with and evaluate the prevalence and use of web content management systems.
A Content Management System (CMS) is a software platform that allows users to create, edit, organise, and publish digital content via a graphical interface — without requiring direct coding knowledge. CMSs power approximately 43% of all websites on the internet (W3Techs, 2024).
| CMS Type | Examples | Evaluation |
|---|---|---|
| Traditional (Coupled) | WordPress, Drupal, Joomla | Pros: All-in-one, large plugin ecosystem, easy for non-developers. Cons: Tightly coupled front-end limits design flexibility; common target for security exploits due to widespread use. |
| Headless CMS | Contentful, Sanity, Strapi | Pros: Content served via API to any front-end (web, mobile, IoT); maximum design flexibility; better performance. Cons: Requires developer to build the front-end separately; higher initial complexity. |
| Visual / No-Code | Webflow, Squarespace, Wix | Pros: Drag-and-drop interface; fast deployment; hosted infrastructure included. Cons: Limited customisation; vendor lock-in; less suited for complex custom functionality. |
🏗️ Data Flow Diagram - CMS Architecture
Comparing coupled vs headless approaches
This diagram contrasts traditional monolithic CMS with headless CMS architecture. Traditional systems tightly couple the back-end database and logic to a single front-end presentation layer. Headless CMS decouples the back-end API from the presentation layer, allowing the same content API to serve multiple front-ends (web, mobile, IoT, etc.) independently.
━━━━━━━━━━━━━━━"] TUI["Admin UI
Build, edit, publish"] TBE["Back-End
Database + Logic"] TFE["Front-End
Theme/Template
HTML + CSS"] TUI -->|Tightly Coupled| TBE TBE -->|Tightly Coupled| TFE end subgraph Headless["Headless CMS
━━━━━━━━━━━━━━━"] HUI["Admin UI
Build, edit, publish"] HBE["Back-End API
Database + Logic"] HFE1["Web Front-End
React/Vue/etc"] HFE2["Mobile App
iOS/Android"] HFE3["IoT Dashboard
Device UI"] HUI -->|Decoupled| HBE HBE -->|JSON API| HFE1 HBE -->|JSON API| HFE2 HBE -->|JSON API| HFE3 end style Traditional fill:#FFCCBC,stroke:#E64A19,stroke-width:2px style Headless fill:#C8E6C9,stroke:#2E7D32,stroke-width:2px style TUI fill:#FFF9C4,stroke:#F57F17 style TBE fill:#E3F2FD,stroke:#1976D2 style TFE fill:#F8BBD0,stroke:#C2185B style HUI fill:#FFF9C4,stroke:#F57F17 style HBE fill:#E3F2FD,stroke:#1976D2 style HFE1 fill:#F8BBD0,stroke:#C2185B style HFE2 fill:#F8BBD0,stroke:#C2185B style HFE3 fill:#F8BBD0,stroke:#C2185B
Purpose: Understand architectural differences and why headless CMS provides flexibility for multiple platforms
Syllabus Link: SE-12-06
Try This: Deploy a headless CMS (e.g., Strapi) and consume its API from both a web front-end and a mobile app to experience the flexibility
⚙️ Assessing Back-End Contribution
🎯 (SE-12-07)
📌 Assess the contribution of back-end web development to the success of a web application.
Back-end development is responsible for all logic that occurs on the server — the invisible engine that powers every user-facing feature. Its contribution to project success encompasses several critical dimensions:
🖥️ Technology Selection
The choice of back-end framework determines the project's scalability, maintainability, and development speed. Django (Python) provides a "batteries-included" approach with an ORM, admin panel, and authentication built in — accelerating development of data-heavy applications. Node.js/Express enables the same language (JavaScript) on front-end and back-end, simplifying the development team's skill requirements. Flask offers a minimal, flexible microframework for APIs. The right technology choice directly impacts delivery timelines and long-term maintenance cost.
⚠️ Business Logic and Data Integrity
The back end enforces all business rules that protect data integrity. For example, validating that a user's age is above 18 before processing a purchase, calculating order totals including applicable tax rates, or checking inventory levels before confirming a stock reservation. Enforcing these rules on the server (rather than only client-side) is essential because client-side code can be bypassed by malicious users using browser developer tools.
🔐 Security Enforcement
The back end is the primary security boundary of a web application. It implements authentication (password hashing with bcrypt, JWT token management), authorisation (role-based access control), input sanitisation (preventing SQL injection and XSS), and rate limiting (preventing brute-force login attacks). A poorly secured back end exposes the entire database and all user data to attackers.
🔄 The Back-End Web Request Process
🎯 (SE-12-07)
📌 Observe and describe the back-end process used to manage a web request from receipt to response.
🔄 The Request-Response Lifecycle
💻 Developing Web Applications & Shell Scripting
🎯 (SE-12-02)
📌 Develop a web application using an appropriate scripting language, and use shell scripts to make files and directories and search for text in files.
# Create project directory structure
mkdir -p my-webapp/{static/{css,js,images},templates,routes}
# Create starter files
touch my-webapp/app.py my-webapp/requirements.txt
# Navigate into project
cd my-webapp
# Search for all TODO comments in Python files
grep -rn "TODO" --include="*.py" .
# Search for a specific function name across all JS files
grep -rn "handleLogin" --include="*.js" static/js/
# List all files modified in the last 24 hours
find . -name "*.py" -mtime -1
# Count lines in all HTML template files
find templates/ -name "*.html" | xargs wc -l
mkdir -p creates nested directories recursively; touch creates empty files; grep -rn searches recursively with line numbers; find locates files by name, type, or modification time.
🖱️ JavaScript DOM Manipulation
🎯 (SE-12-02)
📌 Develop client-side scripts that dynamically update page content using the Document Object Model (DOM).
The Document Object Model (DOM) is a programming interface that represents an HTML page as a tree of objects. JavaScript can read and modify any part of this tree — changing text, styles, attributes, and structure in real time without a page reload. Events such as click, submit, and DOMContentLoaded allow scripts to respond to user actions.
✅ Form Validation with DOM Manipulation
A common use case is validating a registration form on the client side before submitting data to the server. The script below listens for the form's submit event, prevents the default browser action, and runs custom validation logic.
// DOM Manipulation - updating page content dynamically
document.addEventListener('DOMContentLoaded', function() {
const form = document.getElementById('registrationForm');
const messageDiv = document.getElementById('message');
form.addEventListener('submit', function(event) {
event.preventDefault();
const username = document.getElementById('username').value.trim();
const email = document.getElementById('email').value.trim();
const password = document.getElementById('password').value;
if (validateForm(username, email, password)) {
messageDiv.innerHTML = '<p class="success">Registration successful!</p>';
messageDiv.style.display = 'block';
}
});
});
function validateForm(username, email, password) {
const errors = [];
if (username.length < 3 || username.length > 20) {
errors.push('Username must be 3-20 characters');
}
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
errors.push('Invalid email format');
}
if (password.length < 8) {
errors.push('Password must be at least 8 characters');
}
if (errors.length > 0) {
document.getElementById('errors').innerHTML = errors.map(e => `<li>${e}</li>`).join('');
return false;
}
return true;
}
document.getElementById() selects an element by its id attribute; element.addEventListener() attaches an event listener; event.preventDefault() stops the browser's default behaviour (e.g., form submission); element.innerHTML sets or gets HTML content inside an element.
🧪 Form Validation Test Data
When testing form validation, boundary cases, invalid formats, and malicious inputs should all be included in the test plan.
| Test Case | Input | Expected Result | Pass/Fail |
|---|---|---|---|
| Username too short (below minimum) | username: ab |
Error: "Username must be 3-20 characters" | |
| Username at minimum boundary | username: abc |
Validation passes for username field | |
| Username exceeds maximum boundary | username: averylongusernamethatiswaytoolong (21+ chars) |
Error: "Username must be 3-20 characters" | |
| Invalid email format (missing @) | email: notanemail.com |
Error: "Invalid email format" | |
| Empty required field | username: (empty string) |
Error: "Username must be 3-20 characters" | |
| Password too short (below minimum) | password: pass (4 chars) |
Error: "Password must be at least 8 characters" | |
| SQL injection attempt | username: ' OR '1'='1 |
Client-side: treated as a string, regex check may pass — server must sanitise | |
| XSS attempt in username field | username: <script>alert('xss')</script> |
Client-side: length check fails (too long) or server escapes output — no script executes |
⚖️ Client-Side vs Server-Side Validation
| Aspect | Client-Side (JavaScript) | Server-Side (Python / Flask / Django) |
|---|---|---|
| Speed | Instant feedback — no network request needed | Requires a round-trip to the server (adds latency) |
| Security | Can be bypassed — attacker can disable JS or send raw HTTP requests | Cannot be bypassed — server always processes the data |
| Use case | UX improvement — immediate error messages guide the user | Security enforcement — the authoritative check before data is stored |
| Required? | Optional but recommended for usability | Always required — never optional |
📡 Fetch API & AJAX (Asynchronous Requests)
The Fetch API allows JavaScript to make HTTP requests to a server in the background without reloading the page — this pattern is known as AJAX (Asynchronous JavaScript and XML). Modern JavaScript uses the async/await syntax to write asynchronous code that reads like synchronous code, making it easier to follow and debug.
// Fetching data from an API (async/await pattern)
async function loadUserData(userId) {
try {
const response = await fetch(`/api/users/${userId}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('token')}`
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
displayUser(data);
} catch (error) {
console.error('Failed to load user:', error);
showErrorMessage('Could not load user data. Please try again.');
}
}
function displayUser(user) {
document.getElementById('userName').textContent = user.name;
document.getElementById('userEmail').textContent = user.email;
}
.then() handlers. async/await (introduced in ES2017) is syntactic sugar over Promises — the await keyword pauses execution inside an async function until the Promise resolves, making asynchronous code read top-to-bottom like synchronous code. All three patterns are functionally equivalent; async/await is the modern standard.
fetch() call only rejects (throws an error) on network failure. An HTTP 404 or 500 response is considered a successful fetch — it does not throw automatically. Always check response.ok (which is true for status codes 200–299) and manually throw an error if needed, as shown above. Wrap in try/catch to handle both network errors and manually thrown errors.
🌐 CORS — Cross-Origin Resource Sharing
Browsers enforce the same-origin policy: a script running on
https://myapp.com is blocked from making fetch requests to https://api.otherdomain.com unless the server explicitly allows it. This protects users from malicious websites silently reading their data from other services.
Cross-Origin Resource Sharing (CORS) is the mechanism by which a server uses HTTP response headers to tell the browser which external origins are permitted to read its responses.
Configuring CORS in Flask:
Install the
flask-cors package and add: from flask_cors import CORS, then CORS(app, origins=["https://myapp.com"]). For development you may use origins="*" (allow all), but never use this in production.
Configuring CORS in Django:
Install
django-cors-headers, add 'corsheaders' to INSTALLED_APPS, add CorsMiddleware to MIDDLEWARE, and set CORS_ALLOWED_ORIGINS = ["https://myapp.com"] in settings.py.
Common CORS errors students encounter:
- "Access to fetch at '...' from origin '...' has been blocked by CORS policy" — the server is not sending the correct
Access-Control-Allow-Originheader. - Preflight (OPTIONS) request fails — the server must also handle the HTTP OPTIONS method for routes that receive cross-origin requests with custom headers.
- Credentials not included — if using cookies or auth headers cross-origin, both the server must set
Access-Control-Allow-Credentials: trueand the fetch call must includecredentials: 'include'.
🗄️ Web-Based Databases & SQL
🎯 (SE-12-06, SE-12-08)
📌 Apply a web-based database and construct scripts that execute SQL to manage and retrieve application data.
-- Selecting specific fields
SELECT first_name, last_name, email
FROM users
WHERE is_active = 1;
-- Common query: find all orders above a price threshold
SELECT order_id, total_price, order_date
FROM orders
WHERE total_price > 100.00
ORDER BY order_date DESC;
-- GROUP BY: total revenue per product category
SELECT category, SUM(price) AS total_revenue, COUNT(*) AS num_orders
FROM products
JOIN order_items ON products.product_id = order_items.product_id
GROUP BY category
ORDER BY total_revenue DESC;
-- INNER JOIN: link users to their orders
SELECT users.first_name, users.last_name, orders.order_id, orders.total_price
FROM users
INNER JOIN orders ON users.user_id = orders.user_id
WHERE users.country = 'Australia';
-- Complex example: developers and their total game costs (Course Spec p. 23)
SELECT Developers.First_name, Developers.Last_name, SUM(Games.cost) AS Totalcost
FROM Games, Publishers, Developers
WHERE Publishers.Name = 'Games Inc'
AND Publishers.Publisher_ID = Games.Publisher_ID
AND Developers.Developer_ID = Games.Developer_ID
GROUP BY Developers.Developer_ID
ORDER BY Developers.Last_name DESC;
📜 Common SQL Statement Reference
| Statement | Purpose | Example |
|---|---|---|
SELECT | Retrieve records from a table | SELECT * FROM products; |
INSERT INTO | Add a new record | INSERT INTO users (name, email) VALUES ('Alice', 'a@b.com'); |
UPDATE | Modify existing records | UPDATE products SET price = 29.99 WHERE id = 5; |
DELETE | Remove records | DELETE FROM sessions WHERE expires_at < NOW(); |
WHERE | Filter records by condition | WHERE status = 'active' AND age > 18 |
GROUP BY | Aggregate rows by column value | GROUP BY category (used with SUM, COUNT, AVG) |
INNER JOIN | Return rows with matching keys in both tables | JOIN orders ON users.id = orders.user_id |
LEFT JOIN | Return all rows from left table; NULL for non-matching right | Useful for "users who have no orders" |
🔁 Comparing ORM to SQL
🎯 (SE-12-06, SE-12-08)
📌 Compare Object-Relational Mapping (ORM) to raw SQL for interacting with web application databases.
| Method | Description | Pros & Cons |
|---|---|---|
| 🛠️ Raw SQL | Queries written directly in SQL and sent to the database engine. Provides fine-grained control over every aspect of the query. | Pros: Maximum performance; expressive power for complex JOINs, subqueries, and aggregations; universal — works with any SQL database. Cons: Vulnerable to SQL injection if inputs aren't parameterised; verbose for simple CRUD operations; query strings are hard to refactor. |
| 🛠️ ORM | Maps database tables to Python/JavaScript classes. Developers interact with objects; the ORM generates SQL automatically (e.g., Django ORM, SQLAlchemy, Sequelize). | Pros: Faster development for standard operations; built-in input sanitisation prevents injection; database-agnostic (swap PostgreSQL for MySQL with minimal changes); code is more readable and object-oriented. Cons: Can generate inefficient SQL for complex queries; adds an abstraction layer that obscures what is actually executed; requires learning the ORM API on top of SQL. |
# ── RAW SQL approach (using parameterised query for safety) ──
import sqlite3
conn = sqlite3.connect('store.db')
cursor = conn.cursor()
cursor.execute("SELECT name, price FROM products WHERE category = ?", ('Electronics',))
results = cursor.fetchall()
# ── DJANGO ORM equivalent ──
from .models import Product
results = Product.objects.filter(category='Electronics').values('name', 'price')
# Django automatically generates: SELECT name, price FROM products WHERE category = 'Electronics'
🤝 Collaborative Work Practices
🎯 (SE-12-05, SE-12-09)
📌 Describe how collaborative work practices between front-end and back-end developers improve the development of a web solution.
📜 API Contracts and Documentation
The primary collaboration mechanism between front-end and back-end developers is the API contract — an agreed-upon specification of every endpoint's URL, HTTP method, request parameters, and response format. Tools like OpenAPI/Swagger allow teams to document and even mock APIs before the back end is fully built, enabling front-end and back-end development to proceed simultaneously. This prevents integration errors at the end of the project and enables both teams to work independently with confidence.
🔀 Version Control and Branching Strategies
Teams use Git branching workflows to manage parallel development. In the Git Flow model: the main branch always contains production-ready code; develop is the integration branch for completed features; and individual feature/ branches are created for each task. Pull Requests (PRs) are submitted when a feature is complete — requiring at least one peer code review before merging. This enforces code quality and knowledge sharing across the team, and ensures no one developer is a single point of failure for any part of the system.
⚖️ Open-Source and Ethical Collaboration
Collaborative web development carries ethical responsibilities. Teams must fairly attribute contributions, respect the licences of all third-party code used, ensure equitable division of workload, and maintain transparent communication with stakeholders about progress and setbacks. When using open-source code libraries, teams must monitor for security vulnerabilities and update dependencies promptly to protect users (Outcome SE-12-05).
📱 Designing & Implementing a Progressive Web App
🎯 (SE-12-02, SE-12-03, SE-12-06)
📌 Design, develop and implement a Progressive Web App applying UI/UX design principles and accessibility standards.
🎨 UI and UX Principles
🖋️ Typography
Select legible, web-safe or Google Fonts typefaces. Establish a clear typographic hierarchy (H1 → H2 → body → caption). Minimum body font size of 16px for readability. Sufficient line-height (1.5–1.7) for comfortable reading. Limit typeface count to 2 maximum.
🎨 Colour
Use a defined colour palette: primary, secondary, and accent colours plus semantic colours (danger red, success green). Ensure a minimum WCAG AA contrast ratio of 4.5:1 between text and background. Avoid conveying information by colour alone (for colour-blind users).
🔊 Audio and Video
Provide controls for all auto-playing media. Supply captions/subtitles for video content (WCAG requirement). Compress media for fast loading. Avoid content that flashes more than 3 times per second (seizure risk).
🧭 Navigation
Consistent navigation structure across all views. Clear visual indication of the current page (active state). Breadcrumbs for deep navigation hierarchies. Touch-friendly tap targets (minimum 44×44px). Logical tab order for keyboard navigation.
✅ 5-Point Syllabus Compliance Checklist for PWA UX
Ensure your software engineering project meets these core NESA user experience standards:
- Responsiveness: Adapts cleanly to mobile, tablet, and desktop viewports.
- Accessibility: Achieves WCAG AA contrast and full keyboard operability.
- Offline Grace: Displays a custom UI (via Service Worker) when the network drops, rather than the browser's default error.
- Installability: Provides a valid
manifest.jsonso the app can be pinned to the home screen. - Consistency: Uses a predictable interaction model and uniform colour palette across all screens.
♿ Accessibility and Inclusivity
PWA interfaces must be designed to be usable by everyone, including people with visual, auditory, cognitive, or motor disabilities:
<button> for buttons, <nav> for navigation, <main> for content). Screen readers rely on semantic structure to describe pages to blind users.alt attribute text. Decorative images use alt="" so screen readers skip them.aria-label, aria-expanded, role) describe the state and purpose of dynamic UI components to assistive technologies.⚙️ Core PWA Technical Requirements
📄 Web App Manifest
A JSON file (manifest.json) that defines the app's name, icons, theme colour, and display mode (fullscreen/standalone). Enables the "Add to Home Screen" install prompt in mobile browsers.
⚙️ Service Worker
A JavaScript file that runs in the background as a network proxy. Intercepts fetch requests to serve cached assets when offline, enable push notifications, and implement background sync for reliable data submission.
🔒 HTTPS Required
PWAs must be served over HTTPS — service workers are restricted to secure origins. HTTPS also builds user trust and is a requirement for browser installability.
const CACHE_NAME = 'pwa-cache-v1';
const ASSETS_TO_CACHE = ['/', '/index.html', '/css/styles.css', '/js/app.js'];
// Install event: cache core app shell assets
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME).then(cache => cache.addAll(ASSETS_TO_CACHE))
);
});
// Fetch event: serve from cache, fallback to network
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request).then(cached => cached || fetch(event.request))
);
});
📄 Web App Manifest
The manifest.json file tells the browser how to install and present the PWA. Link it in your HTML <head>: <link rel="manifest" href="/manifest.json">
{
"name": "HSC Study Planner",
"short_name": "StudyApp",
"description": "A PWA for organising HSC study sessions",
"start_url": "/index.html",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#4f46e5",
"orientation": "portrait",
"icons": [
{ "src": "/icons/icon-192.png", "sizes": "192x192", "type": "image/png" },
{ "src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png" }
]
}
⚖️ PWA vs Native App
| Feature | PWA | Native App |
|---|---|---|
| Installation | Add to home screen via browser | App Store / Play Store download |
| Offline capability | Yes — via service worker cache | Yes — full local storage |
| Performance | Good — limited by browser | Excellent — direct hardware access |
| Updates | Instant — update the web files | User must download update |
| Device features | Limited (camera, GPS, notifications) | Full access to all device APIs |
| Development cost | Low — one codebase for all platforms | High — separate iOS and Android teams |
🔌 REST API Design
🎯 (SE-12-02, SE-12-03, SE-12-06)
📌 Design and implement RESTful APIs that follow standard conventions for URLs, HTTP methods, and status codes to enable reliable client-server communication.
📏 REST Principles
📡 HTTP Methods
| Method | Purpose | Idempotent? | Has Body? | Example |
|---|---|---|---|---|
GET | Retrieve a resource | Yes | No | GET /api/books |
POST | Create a new resource | No | Yes | POST /api/books |
PUT | Replace a resource entirely | Yes | Yes | PUT /api/books/1 |
PATCH | Partially update a resource | No | Yes | PATCH /api/books/1 |
DELETE | Remove a resource | Yes | No | DELETE /api/books/1 |
🔢 HTTP Status Codes
| Code | Meaning | When Used |
|---|---|---|
| 200 OK | Success | GET request returned data, PUT/PATCH succeeded |
| 201 Created | Resource created | POST request created a new resource |
| 204 No Content | Success, no body | DELETE succeeded, nothing to return |
| 400 Bad Request | Invalid request | Missing required field, malformed JSON |
| 401 Unauthorised | Authentication required | Missing or invalid API key / JWT token |
| 403 Forbidden | Authenticated but no permission | Trying to delete another user's resource |
| 404 Not Found | Resource doesn't exist | GET /api/books/999 — book 999 not in database |
| 422 Unprocessable Entity | Validation failed | Field present but fails validation (e.g., email without @) |
| 429 Too Many Requests | Rate limit exceeded | Client is sending too many requests per minute |
| 500 Internal Server Error | Server bug | Unhandled exception in server code |
| 503 Service Unavailable | Server down/overloaded | Database is down, server is restarting |
🔗 RESTful URL Design
| Bad URL | Good URL | Why |
|---|---|---|
/getBooks | GET /api/books | Use HTTP method, not verbs in URL |
/book/1 | /api/books/1 | Use plural nouns for collections |
/deleteUser?id=5 | DELETE /api/users/5 | Use HTTP DELETE method |
/api/getAuthorBooks?author=3 | GET /api/authors/3/books | Nest related resources in URL |
🧪 Flask REST API — Full CRUD Example
from flask import Flask, request, jsonify
app = Flask(__name__)
# In-memory "database"
books = [
{"id": 1, "title": "Clean Code", "author": "Robert Martin"},
{"id": 2, "title": "The Pragmatic Programmer", "author": "Hunt & Thomas"}
]
next_id = 3
# GET all books
@app.route('/api/books', methods=['GET'])
def get_books():
return jsonify(books), 200
# GET single book
@app.route('/api/books/<int:book_id>', methods=['GET'])
def get_book(book_id):
book = next((b for b in books if b['id'] == book_id), None)
if book is None:
return jsonify({'error': 'Book not found'}), 404
return jsonify(book), 200
# POST — create new book
@app.route('/api/books', methods=['POST'])
def create_book():
global next_id
data = request.get_json()
if not data or 'title' not in data or 'author' not in data:
return jsonify({'error': 'title and author required'}), 400
new_book = {'id': next_id, 'title': data['title'], 'author': data['author']}
books.append(new_book)
next_id += 1
return jsonify(new_book), 201
# DELETE
@app.route('/api/books/<int:book_id>', methods=['DELETE'])
def delete_book(book_id):
global books
original_len = len(books)
books = [b for b in books if b['id'] != book_id]
if len(books) == original_len:
return jsonify({'error': 'Book not found'}), 404
return '', 204
if __name__ == '__main__':
app.run(debug=True)
⚛️ Modern JavaScript Frameworks
🎯 (SE-12-03, SE-12-06)
📌 Explore the purpose and structure of JavaScript frameworks and evaluate when a framework is appropriate versus vanilla JavaScript.
❓ Why Frameworks Exist
As web applications grow, manually manipulating the DOM with vanilla JavaScript becomes complex and error-prone. Frameworks solve these problems:
- State management: When data changes, which parts of the page should update? Frameworks handle this automatically.
- Component reuse: Build once, use anywhere — a navigation bar, card, or form component defined once can be used across all pages.
- Data binding: UI automatically reflects data changes without manual DOM manipulation.
⚛️ React — Component-Based UI
React (by Meta/Facebook) uses components — reusable UI building blocks — and a Virtual DOM to efficiently update only the parts of the page that changed.
import { useState } from 'react';
function Counter() {
// useState hook: declares 'count' state, initially 0
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={() => setCount(0)}>Reset</button>
</div>
);
}
export default Counter;
⚖️ Framework Comparison
| Feature | Vanilla JS | React | Vue.js |
|---|---|---|---|
| Learning curve | Low — just JavaScript | Medium — JSX, hooks | Low-Medium — simpler than React |
| Performance | Best (no overhead) | Very good (Virtual DOM) | Very good (Virtual DOM) |
| Ecosystem | Browser APIs only | Huge (npm, CRA, Next.js) | Large (Vite, Nuxt) |
| Job market | Foundation required | Most in-demand | Growing, popular in Asia |
| HSC projects | Perfectly acceptable | Adds complexity for small projects | Gentler learning curve than React |