Building Your First REST API with TypeScript and Express: A Beginner's Guide

Learn how to create your very first REST API using TypeScript and Express. This beginner-friendly guide takes you through every step to build a simple but functional API.

REST APIs allow different software applications to communicate with each other over the internet. In this guide, you'll learn how to create a simple REST API using Express, a popular Node.js web framework, and TypeScript, a typed superset of JavaScript. This tutorial assumes you have Node.js and npm installed on your computer.

### Step 1: Setting Up Your Project First, create a new directory for your project and initialize it with npm:

typescript
mkdir my-first-api
cd my-first-api
npm init -y

### Step 2: Installing Required Packages Next, install Express and TypeScript along with type definitions and some helpful development tools:

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

### Step 3: Configuring TypeScript Create a tsconfig.json file to configure TypeScript options. Run this command to generate a default configuration file:

typescript
npx tsc --init

You can keep most default settings. Just make sure to set the target to at least ES6 for modern JavaScript features like this:

typescript
"target": "ES6",

### Step 4: Writing Your First API Endpoint Create a `src` folder and inside it a file named `index.ts`. This will be the main file of your application. Add the following code to create a simple Express server with one GET endpoint:

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

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

// Middleware to parse JSON
app.use(express.json());

// Simple GET endpoint
app.get('/', (req: Request, res: Response) => {
  res.send('Welcome to your first REST API built with TypeScript and Express!');
});

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

### Step 5: Running Your Server To run your server easily with automatic restarts on file changes, add this script to your `package.json`:

typescript
"scripts": {
  "start": "nodemon src/index.ts"
}

Now start your server with:

typescript
npm start

Open your browser and go to http://localhost:3000. You should see your welcome message.

### Step 6: Adding a RESTful Resource Let's add a simple resource: an array of users. We'll create routes to retrieve all users and add new users.

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

const users: User[] = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
];

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

// Add a new user
app.post('/users', (req: Request, res: Response) => {
  const newUser: User = {
    id: users.length + 1,
    name: req.body.name,
  };
  users.push(newUser);
  res.status(201).json(newUser);
});

### Step 7: Testing Your API You can test your API using tools like Postman, Insomnia, or even curl in the terminal. To get all users, send a GET request to: http://localhost:3000/users To add a user, send a POST request to: http://localhost:3000/users with a JSON body like:

typescript
{
  "name": "Charlie"
}

Your server will respond with the newly created user including an ID.

### Conclusion Congratulations! You've built a basic REST API with TypeScript and Express. From here, you can expand by connecting a database, adding validation, authentication, and more complex routes. TypeScript helps you write safer, more predictable code by catching errors early and providing helpful autocompletion.