0% found this document useful (0 votes)
1 views33 pages

Topic 1 Node.js Web API

This document outlines the fundamentals of Full Stack Secured Development using Node.js, focusing on the creation and management of RESTful APIs with Express.js. It covers key concepts such as HTTP methods, routes, endpoints, and the use of npm for package management. Additionally, it introduces tools like Postman for API testing and useful packages like nodemon and dotenv for development efficiency.

Uploaded by

solrflam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views33 pages

Topic 1 Node.js Web API

This document outlines the fundamentals of Full Stack Secured Development using Node.js, focusing on the creation and management of RESTful APIs with Express.js. It covers key concepts such as HTTP methods, routes, endpoints, and the use of npm for package management. Additionally, it introduces tools like Postman for API testing and useful packages like nodemon and dotenv for development efficiency.

Uploaded by

solrflam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Official (Closed) and Non-Sensitive

Full Stack Secured Development

Node.js Web API

COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

Learning Outcomes

By the end of this lesson, you will be able to:


1. Explain the role of Node.js in Full Stack Development.
2. Define what a RESTful API is.
3. Discuss how to use Express.js for building web APIs.
4. Outline some useful packages.

COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

Node.js

COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

Full Stack Development

Full stack development refers to the end-to-end web application


development, including the front-end and back-end.
Full Stack Development

Database

Front-end Back-end

Other Systems
COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

Node.js for Back-end

Node.js is an open-source, server-side JavaScript runtime environment.


• Asynchronous: uses an event-driven, non-blocking I/O model
• Scalability: can handle a large number of requests and processing tasks
• Speed: popular choice for building high-performance web applications
• Cross-platform: can run on different operating systems

node -v # check version


COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

Hello Node.js
Simple code example to print "Hello, Node.js!" to the console

app.js

console.log("Hello, Node.js!"); • Create a JavaScript file

Open terminal or command prompt

> cd /path/to/your/directory • Navigate to the file directory

> node app.js • Run Node.js script

Output:

Hello, Node.js!

COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

npm
npm (Node Package Manager) is a tool for managing JavaScript packages in Node.js projects.
It is bundled with Node.js by default.

• npm init -y # -y: use default options • npm uninstall <package>


• npm install # shorthand: “npm i” • npm update
• npm install <package> • npm run <script>
• npm install <package>@<version>
• npm install -g <package> # -g: install globally
• npm install --save-dev <package> # --save-dev: save as development dependency

npm -v # check version


COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

package.json
{ • The package.json file is a JSON file
"name": "my-node-app",
"version": "1.0.0",
that serves as the manifest for
"description": "A simple Node.js application", Node.js projects.
"main": "index.js",
"dependencies": {
"express": "^4.18.2" • It contains metadata about the
},
"devDependencies": { project, including its name, version,
"nodemon": "^2.0.13" dependencies, scripts, and other
}, important information.
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
},
"author": "Your Name",
"license": "MIT"
}

COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

Code Editor
• Visual Studio Code (VS Code) is a popular code editor. It includes IntelliSense for Node.js by default.

Useful extensions:

• Help you to code faster, free for students

• Nice colourful icons for folders and files

COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

RESTful API

COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

RESTful API

A RESTful API, or Representational State Transfer API, is a set of principles for designing
and structuring web services.
• Resource-Based: identify the resources that the API exposes (e.g. user, product)
• CRUD Operations: CRUD stands for Create, Read, Update, and Delete
• Uniform Interface: use HTTP methods, URLs and JSON data
• Statelessness: not rely on any previous request or server session

request
response

COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

HTTP Methods

HTTP (Hypertext Transfer Protocol) defines a set of request methods


that are used by the client to send requests to the server.
• GET: read data from resource(s)
• POST: create a new resource
• PUT: update an existing resource
• DELETE: delete a resource

COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

Routes and Endpoints

• Route: A route is a path that defines a specific resource or a group of related


resources within the API. (e.g. “/product”)

• Endpoint: An endpoint is a specific URL pattern within a route, and it's


associated with an HTTP method.
• GET /product
• GET /product/{id}
• POST /product
• PUT /product/{id}
• DELETE /product/{id}
COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

HTTP Status Codes


HTTP uses response status codes to indicate the result of a client's request to the
server.
• 200 OK: The request was successful, and the server has returned the requested
data
• 400 Bad Request: Invalid syntax or missing information in the request
• 401 Unauthorized: The client is not authorized to access the requested resource
• 403 Forbidden: The client does not have permission to access the requested
resource
• 404 Not Found: The requested resource could not be found on the server
• 500 Internal Server Error: The server encountered an unexpected error

COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

JSON for Data

JSON (JavaScript Object Notation) is a JSON for list of users


lightweight data interchange format that {
is commonly used in API request and "users": [
{
response bodies. "name": "John Doe",
"email": "[email protected]",
JSON for one user "age": 30
},
{ {
"name": "John Doe", "name": "Jane Smith",
"email": "[email protected]", "email": "[email protected]",
"age": 30 "age": 25
} }
]
}

COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

Popular Frameworks

• Express.js (Node.js)

• ASP.NET Core (C#)

• Flask (Python)

• Spring Boot (Java)

COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

Testing API

Postman is a popular tool


for testing web APIs.
• Saving requests
• Team collaboration

COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

Express.js

COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

Express.js

Express.js is a popular Node.js framework that provides tools and features for building
RESTful APIs.
npm i express # install express
index.js

const express = require('express'); • Import express and create an application


const app = express();

app.get('/', function (req, res) { • Define a route handler for the root URL
res.send('Hello World');
})

let port = 3001; • Start the server


app.listen(port, () => {
console.log('Sever running');
});

COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

Project Structure
• project-root
• > middlewares (custom middleware functions)
• > models (database models)
• > node_modules (libraries and dependencies generated by npm)
• > routes (API route definition)
• .env (environment variables)
• index.js (entry point of the application)
• package-lock.json (lock file generated by npm)
• package.json (project configuration including dependencies)

COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

Create Route
routes/product.js • Create the route file

const express = require('express'); • Import express and create an express router


const router = express.Router();

const products = [ • Define a list of products


{ id: 1, name: 'Product 1', price: 10.99 },
{ id: 2, name: 'Product 2', price: 19.99 }
];

// Define a GET endpoint to list all products • Define a GET endpoint to list all products
router.get('/', (req, res) => {
res.json(products);
});

module.exports = router; • Export the router

COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

Use Route
index.js

// Import the route • './routes/product' specifies the relative path


const productRoute = require('./routes/product'); to the product.js file

// Mount the route on a specific URL path • All the endpoints defined in the product
app.use('/product', productRoute); route will be under the URL path ‘/product’

route path ‘/product’ + get(‘/’, …) endpoint ‘GET /product’: list all products

This approach allows you to organize your application's routes into modular files and specify where
those routes should be accessible.

COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

POST

endpoint ‘POST /product’: create a new product

routes/product.js

// Define a POST endpoint to create a new product


router.post("/", (req, res) => {
let data = req.body; • Extract data from the request body
products.push(data); • Add data into the array
res.json(data);
}); • Return the data

COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

GET by ID

endpoint ‘GET /product/{id}’: get a product by ID

routes/product.js

// Define a GET endpoint to get a product by ID


router.get('/:id', (req, res) => {
• Extract parameter id from URL
const id = req.params.id;
const product = products.find((p) => p.id === id);
if (!product) { • Check the error Not Found
res.sendStatus(404);
return;
}
• Return the found data
res.json(product);
});

COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

PUT by ID

endpoint ‘PUT /product/{id}’: update a product by ID

routes/product.js

// Define a PUT endpoint to update a product by ID


router.put('/:id', (req, res) => {
• Extract parameter id from URL
const id = req.params.id;
const product = products.find((p) => p.id === id);
if (!product) { • Check the error Not Found
res.sendStatus(404);
return;
}
// TODO: Update the product
res.json({ message: 'Product updated' }); • Update data
});

COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

DELETE by ID

endpoint ‘DELETE /product/{id}’: delete a product by ID

routes/product.js

// Define a DELETE endpoint to delete a product by ID


router.delete('/:id', (req, res) => {
• Extract parameter id from URL
const id = req.params.id;
const product = products.find((p) => p.id === id);
if (!product) { • Check the error Not Found
res.sendStatus(404);
return;
}
// TODO: Delete the product
res.json({ message: 'Product deleted' }); • Delete data
});

COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

Useful Packages

COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

nodemon
nodemon is a tool that helps develop Node.js based applications by automatically
restarting the node application when file changes in the directory are detected.
• It is particularly useful during the development process, as it eliminates the need to
manually stop and restart your application every time you make a code change.
• nodemon is often used in combination with npm scripts. You can define a script in
your package.json file to run your application with Nodemon.
npm i --save-dev nodemon
package.json

"scripts": {
"start": "nodemon index.js" • When you run “npm start”, npm will execute the
} "nodemon index.js" command

COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

dotenv
dotenv package is used to load environment variables from a .env file into the
process.env object.
npm i dotenv

.env
• In the file .env, define your environment-specific
APP_PORT = 3001 configuration variables as key-value pairs.

index.js

require('dotenv').config(); • In your JavaScript code, import the package.


• dotenv loads the variables into the process.env
let port = process.env.APP_PORT; object, making them accessible in your code.

COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

cors

• CORS stands for Cross-Origin Resource Sharing, and it is a security feature


implemented by web browsers.
• By default, web browsers enforce the Same-Origin Policy, which means that a web
page can only make requests to the same domain (origin) from which it was served.
• cors package provides a middleware that can be used to enable cross-origin requests
with various options.
index.js npm i cors
const cors = require('cors');

// Enable CORS • The “app.use” function is used to mount


app.use(cors({ middleware in Express, and in this case, it's
origin: process.env.CLIENT_URL adding the cors middleware to all routes.
}));

COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

Summary

1. Explain the role of Node.js in Full Stack Development.


2. Define what a RESTful API is.
3. Discuss how to use Express.js for building web APIs.
4. Outline some useful packages.

COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.
Official (Closed) and Non-Sensitive

Credits

This learning unit was developed by:


Li Haiyun, School of Information Technology, Nanyang Polytechnic

References:
• Coding stickers created by kerismaker - Flaticon
https://www.flaticon.com/stickers-pack/web-development-195

COPYRIGHT © 2024. SINGAPORE INSTITUTE OF TECHNOLOGY AND NANYANG POLYTECHNIC. ALL RIGHTS RESERVED.

You might also like