Express.js in Action: How to Build an API with Node.js and TypeScript in 2024

In the world of modern web development, creating robust and scalable APIs is essential. Node.js, with its asynchronous, event-driven architecture, paired with the powerful typing capabilities of TypeScript, offers a fantastic environment for building APIs. In this guide, we'll walk through the process of setting up an API using Node.js and Express.js with TypeScript.

 

Why Choose Node.js, Express.js, and TypeScript?

Node.js

Node.js is a runtime environment that allows you to execute JavaScript on the server side. Its non-blocking I/O model makes it efficient and suitable for real-time applications.

 

 Express.js

Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for building web and mobile applications.

 

 TypeScript

TypeScript is a statically typed superset of JavaScript that compiles to plain JavaScript. It helps catch errors early through type checking and improves the developer experience with features like IntelliSense.

 

 Prerequisites

Before we start, ensure you have the following installed on your machine:

- Node.js (version 18 or later)

- npm (Node package manager)

- TypeScript (globally installed via npm)

 

```bash

 Install Node.js and npm from https://nodejs.org/

 Install TypeScript globally

npm install -g typescript

```

 

 Step 1: Setting Up Your Project

 

Create a new directory for your project and navigate into it:

 

```bash

mkdir express-api-ts

cd express-api-ts

```

 

Initialize a new Node.js project:

 

```bash

npm init -y

```

Install the necessary dependencies:

 

```bash

npm install express

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

```

Create a `tsconfig.json` file for TypeScript configuration:

 

```json

{

  "compilerOptions": {

    "target": "ES2020",

    "module": "commonjs",

    "strict": true,

    "esModuleInterop": true,

    "skipLibCheck": true,

    "outDir": "./dist",

    "rootDir": "./src"

  }

}

```

 Step 2: Building the API

 

 Project Structure

Organize your project structure as follows:

 

```

express-api-ts/

├── src/

│   ├── index.ts

│   ├── routes/

│   │   └── user.ts

├── package.json

├── tsconfig.json

```

 Creating the Express Server

 

In `src/index.ts`, set up the Express server:

 

```typescript

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

 

const app: Application = express();

const port: number = 3000;

 

// Middleware to parse JSON requests

app.use(express.json());

 

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

  res.send('Hello, TypeScript with Express!');

});

 

// Import routes

import userRoutes from './routes/user';

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

 

app.listen(port, () => {

  console.log(`Server is running on http://localhost:${port}`);

});

```

 Creating Routes

 

Create a `src/routes/user.ts` file for user-related routes:

 

```typescript

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

 

const router: Router = Router();

 

// A simple GET endpoint

router.get('/', (req: Request, res: Response) => {

  res.json({ message: 'GET all users' });

});

 

// A simple POST endpoint

router.post('/', (req: Request, res: Response) => {

  const { name, email } = req.body;

  res.json({ message: 'User created', user: { name, email } });

});

 

export default router;

```

 Step 3: Running the Server

Modify your `package.json` to include a start script:

 

```json

"scripts": {

  "start": "ts-node-dev --respawn src/index.ts"

}

```

 

Now, run your server:

 

```bash

npm start

```

You should see output indicating that your server is running:

 

```

Server is running on http://localhost:3000

```

 

 Testing Your API

 

Use a tool like Postman or curl to test your API endpoints.

 

 GET all users

 

```bash

curl http://localhost:3000/api/users

```

 

Expected response:

 

```json

{

  "message": "GET all users"

}

```

 

 POST a new user

 

```bash

curl -X POST http://localhost:3000/api/users -H "Content-Type: application/json" -d '{"name": "John Doe", "email": "john@example.com"}'

```

 

Expected response:

 

```json

{

  "message": "User created",

  "user": {

    "name": "John Doe",

    "email": "john@example.com"

  }

}

```

 

 Conclusion

In this tutorial, we've covered the basics of setting up an Express.js API using Node.js and TypeScript. This setup forms a strong foundation for building more complex and scalable applications. Happy coding!