Building a REST API for User Management with Node.js/TypeScript (Part 1: Express.js)
When building a REST API using Node.js, Express.js is always the top choice for handling requests and managing routes. Express.js offers powerful features, flexibility, a small footprint, and is easy to integrate into a project. In this series, we will build a REST API for managing users with Node.js/TypeScript combined with Express.js.
Packages used:
- Express
- Typescript
- Cors: Express middleware used to enable cross-origin resource sharing.
I. Initialize and Install Necessary Packages
First, run the command:
npm init
Next, install the necessary packages with the following command:
npm i express cors
Additionally, we also need to install packages to support development.
npm i –save-dev @types/cors @types/express typescript
After installing the packages, your package.json file will look like this (the version may change depending on the installation time):
II. Project Structure
The basic structure provided here will include 2 files:
- app.ts
- users\users.routes.config.ts
Here we will divide the structure into individual modules, each of which will be responsible for its own logic. The user module will contain all the logic for handling users, and later we will create similar modules like the users module as we expand the system.
In the next article, we will guide you on adding additional folders like middleware, controllers, services, daos, dto within the users module to clearly separate the responsibilities of each layer.
III. Implementing Routes and Entry Point in app.ts
Inside the users folder, create the file users.routes.config.ts as follows:
import express from 'express'; export class UsersRoutes { app: express.Application constructor(app: express.Application) { this.app = app; this.configureRoutes(); } configureRoutes() { this.app.route(`/users`) .get((req: express.Request, res: express.Response) => { res.status(200).send(`List of users`); }) .post((req: express.Request, res: express.Response) => { res.status(200).send(`Post to users`); }); this.app.route(`/users/:userId`) .get((req: express.Request, res: express.Response) => { res.status(200).send(`GET requested for id ${req.params.userId}`); }) .put((req: express.Request, res: express.Response) => { res.status(200).send(`PUT requested for id ${req.params.userId}`); }) .patch((req: express.Request, res: express.Response) => { res.status(200).send(`PATCH requested for id ${req.params.userId}`); }) .delete((req: express.Request, res: express.Response) => { res.status(200).send(`DELETE requested for id ${req.params.userId}`); }); return this.app; } }
This UsersRoutes class will initialize and define the routes for the users module. It helps modularize the route code, making development and maintenance easier.
- Request: This object contains information about the client request, including information about headers, params, query, body, and other attributes.
- Response: This object represents the response sent from the server to the client after processing the request. It provides methods for sending data, setting headers, and status codes for the response.
Next, we will implement the entry point app.ts with the following content:
import * as bodyparser from 'body-parser'; import cors from 'cors'; import express from 'express'; import * as http from 'http'; import { UsersRoutes } from './users/users.routes.config'; const app: express.Application = express(); const port = 3000; app.use(bodyparser.json()); app.use(cors()); new UsersRoutes(app); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });
You can see a new package that has been imported into the processing:
body-parser is a middleware in Express.js used to extract data from the body of an HTTP request sent from the client.
The express() function is used to create an Express application. When you call express(), it creates an instance of the Express application. This app object has many methods to define routes, use middleware, and handle other HTTP requests.
After initializing the Express app, we apply the 2 middleware: bodyparser and cors, then create an instance of the UsersRoutes class. Inside the constructor of the UsersRoutes class, we call the configureRoutes() method, which initializes the user routes in the Express app.
Finally, we call the app.listen() method in Express.js to start the server and listen for client connections on a specific port (3000 in this case).
IV. Configuring TypeScript and package.json
In the previous step, we completed the implementation of the source code. Just a few configurations are needed to start the server.
First, create a tsconfig.json file with the following content:
{ "compilerOptions": { "target": "es2016", // Specify ECMAScript version that TypeScript will compile to "module": "commonjs", // Module type used in compiled code (here is CommonJS) "outDir": "./dist", // Path to the directory containing the compiled JavaScript code "strict": true, // Enable strict type checking "esModuleInterop": true, // Allows for compatibility with TypeScript and JavaScript modules "inlineSourceMap": true // If true, source maps will be embedded directly into the JavaScript file } }
Next, adjust the scripts section of the package.json file
"scripts": { "start": "tsc && node ./dist/app.js", "debug": "export DEBUG=* && npm start", "test": "echo \"Error: no test specified\" && exit 1" }
In the start script, tsc will compile the TypeScript files into JavaScript based on the configuration set in tsconfig.json into the dist directory. Then, Node.js will execute the JavaScript file app.js.
V. Test API
Run the application using the command:
npm start
To test if the APIs are working, you can use curl (on Linux) or Invoke-WebRequest (on Windows):
For the GET method:
curl –request GET ‘localhost:3000/users/12345’ Invoke-WebRequest -Uri ‘http://localhost:3000/users/12345’ -Method Get
Or the POST method:
curl –request POST ‘localhost:3000/users’ \ –data-raw ” Invoke-WebRequest -Uri ‘http://localhost:3000/users’ -Method Post -ContentType ‘application/json’ -Body ‘{}’
We have now completed the basic framework of the application. In the next part, we will continue implementing Services, Middleware, Controllers, and Models for the users module.
See you in the next part.
![]() | Vắn Quang Quí PHP Developer |