Node + Express + TypeScript: Create a simple REST API

Updated: December 28, 2023 By: Guest Contributor Post a comment

Overview

Creating REST APIs with Node.js, Express, and TypeScript is a powerful combination for backend development. Node.js and Express form a well-known duo for building scalable and flexible server-side applications. TypeScript adds static typing to the mix, enhancing code quality and predictability. This tutorial will guide you through the process of creating a simple REST API from scratch using these three technologies.

Setting Up the Project

First, let’s set up a new Node.js project using npm:

$ mkdir my-api
$ cd my-api
$ npm init -y

Next, install the necessary packages:

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

Configuring TypeScript

Create a ‘tsconfig.json’ file to configure TypeScript options:

{
    "compilerOptions": {
        "target": "es2020",
        "module": "commonjs",
        "rootDir": "./src",
        "outDir": "./dist",
        "esModuleInterop": true,
        "strict": true
    }
}

Building the Express Server

Setup the basic server by creating an ‘index.ts’ file in the ‘src’ directory:

import express from 'express';

const app = express();
const port = 3000;

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

app.listen(port, () => {
    console.log(`Server running on port ${port}`);
});

Creating the REST API

Now it’s time to build our REST API endpoints. We’ll begin by implementing basic CRUD operations for a simple resource, like ‘items’.

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

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

const items: Item[] = [];

const app = express();
app.use(express.json());

app.get('/items', (req: Request, res: Response) => {
    res.json(items);
});

app.post('/items', (req: Request, res: Response) => {
    const item: Item = req.body;
    items.push(item);
    res.status(201).json(item);
});

// Add the PUT and DELETE endpoints ...

Expanding the API

Consider adding query parameters, pagination logic, and more complex request handling as you advance. Here’s how you might add a query parameter to filter items by name:

app.get('/items', (req: Request, res: Response) => {
    const { name } = req.query;
    const filteredItems = name ? items.filter(item => item.name.includes(name as string)) : items;
    res.json(filteredItems);
});

Error Handling

Implement proper error handling for a more robust API. Use middleware functions for handling different error scenarios:

app.use((err: any, req: Request, res: Response, next: Function) => {
    console.error(err.stack);
    res.status(500).send('Something broke!');
});

Final Words

In this tutorial, we have covered how to set up a basic REST API using Node.js, Express, and TypeScript. We explored setting up the environment, creating a simple server, defining routes, and expanding functionality with query parameters and error handling. To take your skills further, consider adding authentication, connecting to a database, and adhering to API design best practices.

Building APIs with TypeScript adds clarity and type safety, which makes maintaining and scaling your application easier down the road. Experiment with the concepts you’ve learned and integrate other middleware to enhance the capabilities of your Node.js and Express-powered server.