Building a REST API with TypeScript and Express

TypeScript and Express are a powerful combination for building robust REST APIs. TypeScript provides type safety, better tooling, and enhanced development experience, while Express is a minimalist web framework for Node.js. This guide will walk through the steps to build a REST API using TypeScript and Express.

Setting Up the Project

Start by creating a new directory for the project and initializing a Node.js application.

mkdir typescript-express-api
cd typescript-express-api
npm init -y

Next, install the required dependencies for Express and TypeScript.

npm install express
npm install --save-dev typescript ts-node @types/node @types/express

Create a tsconfig.json file to configure TypeScript. Run the following command:

npx tsc --init

Modify the tsconfig.json file to suit the project's needs, enabling options like "strict", "esModuleInterop", and setting the output directory to "dist".

Creating the Express Server

Create a new folder named src and inside it, create a file named index.ts. This file will serve as the entry point for the Express server.

import express, { Request, Response } from 'express';

const app = express();
const PORT = process.env.PORT || 3000;

app.use(express.json());

app.get('/', (req: Request, res: Response) => {
  res.send('Hello, TypeScript and Express!');
});

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

To run the server, use the following command:

npx ts-node src/index.ts

Defining API Routes

Create a new folder inside src named routes. In this folder, create a file named userRoutes.ts to define routes for handling user-related requests.

import { Router, Request, Response } from 'express';

const router = Router();

router.get('/users', (req: Request, res: Response) => {
  res.json({ message: 'Get all users' });
});

router.post('/users', (req: Request, res: Response) => {
  const user = req.body;
  res.json({ message: 'User created', user });
});

export default router;

In the index.ts file, import the userRoutes and use them in the application.

import userRoutes from './routes/userRoutes';

app.use('/api', userRoutes);

Creating a Controller and Service Layer

Organize the code by creating separate layers for controllers and services. Create two new folders inside src: controllers and services.

In the controllers folder, create a file named userController.ts.

import { Request, Response } from 'express';
import { getAllUsers, createUser } from '../services/userService';

export const getUsers = (req: Request, res: Response) => {
  const users = getAllUsers();
  res.json(users);
};

export const addUser = (req: Request, res: Response) => {
  const newUser = req.body;
  const user = createUser(newUser);
  res.json(user);
};

In the services folder, create a file named userService.ts.

interface User {
  id: number;
  name: string;
}

let users: User[] = [];

export const getAllUsers = (): User[] => {
  return users;
};

export const createUser = (user: User): User => {
  users.push(user);
  return user;
};

Update userRoutes.ts to use these controllers:

import { Router } from 'express';
import { getUsers, addUser } from '../controllers/userController';

const router = Router();

router.get('/users', getUsers);
router.post('/users', addUser);

export default router;

Testing the REST API

To test the REST API, use a tool like Postman or curl to send requests to the endpoints. Start the server and make a GET request to /api/users and a POST request to /api/users with a JSON payload.

Conclusion

By following these steps, a REST API can be created using TypeScript and Express. TypeScript adds type safety and a better development experience, while Express provides a simple and powerful framework for building RESTful services. This setup can be further enhanced by adding validation, error handling, and more complex business logic.