A simple REST API Server for Financial Tracking Application, so user can input their assets and get the list of it. This REST API Server is using Node js, TypeScript, and Express that allows users to perform basic CRUD (Creat, Read, Update, Delete) operations on application.
- Intro
- Content
- Tools
- Get Started
- The Installed Package for the Project
- Configuring package.json
- Create app.ts
- Create routes.ts
- Try the API
- Deploy Server on Fly.io
- Git and Github
- Google Chrome
- VS Code
- REST Client Tools(Postman, Thunder Client(VS Code Extension))
- Node Js
- TypeScript
- Express
Before we start to build the server, first you need to downlaod and install Node.Js, choose the latest LTS version of it.
After that, you can start to create your project folder, then open Command Prompt, and type npm init
to initialization npm on project. It will create new file "package.json". You can skip to fill it for now. Next, you can start to install package for your project.
-
npm install -g typescript
for install typescript for global,npm install -D typescript
andnpm install -D @types/node
for install typescript for Developer, next you can usetsc -v
to check the installation version. Installing modules locally allows you to control and share the versions through package.json. ts-node will always resolve the compiler from cwd before checking relative to its own installation. -
npm install express dotenv
for install express js(minimalist web framework for Node.js) and dotenv(storing configuration in the environment separate from code). -
npm install -D @types/express
(This package contains type definitions for Express). -
npm install body-parser
andnpm install -D @types/body-parser
(Node.js body parsing middleware. Parse incoming request bodies in a middleware before your handlers, available under the req.body property.) -
npm i -D concurrently
for run multiple commands concurrently. Like npm run watch-js & npm run watch-less but better. -
npm i -D nodemon
for install nodemon, that is a tool that helps develop Node.js based applications by automatically restarting the node application when file changes in the directory are detected.
Custom script for building, start, and run the server.
"scripts": {
"build": "npx tsc",
"start": "node dist/app.js",
"watch": "concurrently \"npx tsc --watch\" \"nodemon -q dist/app.js\"",
"test": "echo \"Error: no test specified\" && exit 1"
},
This file is for HTTP method(request and response) handlers, to make it connect to server using certain port.
import express from 'express';
import bodyParser from 'body-parser';
import routes from './routes';
import dotenv from 'dotenv';
dotenv.config();
const app = express();
const port = process.env.PORT || 1111;
app.use(bodyParser.json());
app.use('/api', routes);
app.listen(port, () => {
console.log(`The Server is now run on http://localhost:${port}`);
});
This file is for design and implement HTTP method request handlers, that allows users to perform basic CRUD (Create, Read, Update, Delete) operations on transactions.
- Declaration interface for variable data name atributes and it types
interface Financial {
id: number;
type: string;
finance: string;
detail: string;
cash: number;
}
let financial: Financial[] = [
{ id: 1, type: 'Cash In', finance: 'Gajian', detail: 'Gajian Bulanan', cash: 4000000 },
{ id: 2, type: 'Cash Out', finance: 'Belanja', detail: 'Belanja Kebutuhan Bulanan', cash: 500000 },
{ id: 3, type: 'Cash Out', finance: 'Bayar Listrik', detail: 'Bayar Listrik Bulanan', cash: 250000 },
];
- GET all is to show all existing data method
router.get('/financial', (req: Request, res: Response) => {
res.json(financial);
});
- GET by id is to show existing data by id
router.get('/financial/:id', (req: Request, res: Response) => {
const id = parseInt(req.params.id);
const financials = financial.find((p) => p.id === id);
if (financials) {
res.json(financials);
} else {
res.status(404).json({ message: 'Financial is Not Found' });
}
});
- POST is to create new data
router.post('/financial', (req: Request, res: Response) => {
const newFinancial: Financial = {
id: financial.length + 1,
type: req.body.type,
finance: req.body.finance,
detail: req.body.detail,
cash: req.body.cash,
};
financial.push(newFinancial);
res.status(201).json(newFinancial);
});
- PUT by id is to update existing data by id
router.put('/financial/:id', (req: Request, res: Response) => {
const id = parseInt(req.params.id);
const financialIndex = financial.findIndex((p) => p.id === id);
if (financialIndex !== -1) {
const updatedFinancial: Financial = {
id,
type: req.body.type,
finance: req.body.finance,
detail: req.body.detail,
cash: req.body.cash,
};
financial[financialIndex] = updatedFinancial;
res.json(updatedFinancial);
} else {
res.status(404).json({ message: 'Financial is Not Found' });
}
});
- PATCH by id is to partilally update existing data by id
router.patch('/financial/:id', (req: Request, res: Response) => {
const id = parseInt(req.params.id);
const financialIndex = financial.findIndex((p) => p.id === id);
if (financialIndex !== -1) {
const updatedFinancial: Financial = {
...financial[financialIndex],
...req.body,
};
financial[financialIndex] = updatedFinancial;
res.json(updatedFinancial);
} else {
res.status(404).json({ message: 'Financial is Not Found' });
}
});
- DELETE by id is to delete an existing data by id
router.delete('/financial/:id', (req: Request, res: Response) => {
const id = parseInt(req.params.id);
const financialIndex = financial.findIndex((p) => p.id === id);
if (financialIndex !== -1) {
const deletedFinancial = financial.splice(financialIndex, 1)[0];
res.json(deletedFinancial);
} else {
res.status(404).json({ message: 'Financial is Not Found' });
}
});
Before that, make sure we have already build/compile the project and turn on the server using tsc --watch
on terminal.
We will need to try the API using REST client tool, to ensure that it is functioning properly. On this case we will install and use either "Postman" application or anoter application, there are alternative extension app on VS Code, and that is "Thunder Client", which is more lightweight from Postman. In here we will use "Thunder Client".
- GET /financial : Returns a list of all post
- GET /financial/:id : Return a spesific post with the given ID
- POST /financial : Create a new post
- PUT /financial/:id : Updates an existing post with the given ID
- PATCH /financial/:id : Partially update an existing post with the given ID
- DELETE /financial/:id : Deletes an existing post with the given ID
We can deploy our server using deployment platform, on this case we are going to using fly.io platform.
Hostname :
Hostname for transaction :