how-to-build-a-restful-api-with-expressjs-and-typescript.html

How to Build a RESTful API with Express.js and TypeScript

Creating a RESTful API can seem daunting, especially if you're new to web development or programming in general. However, using tools like Express.js and TypeScript can simplify the process significantly. In this article, we will walk you through the steps of building a RESTful API using these technologies, complete with code examples and actionable insights.

What is a RESTful API?

A RESTful API (Representational State Transfer) is a set of conventions for building web services that allow different applications to communicate with each other over HTTP. RESTful APIs use standard HTTP methods such as GET, POST, PUT, and DELETE to perform operations on resources.

Use Cases for RESTful APIs

  • Web Applications: Enabling front-end frameworks (like React, Angular, or Vue.js) to communicate with back-end services.
  • Mobile Applications: Serving data to mobile apps on platforms like iOS and Android.
  • Microservices: Facilitating communication between various microservices in a distributed system.

Setting Up Your Environment

Before diving into code, you’ll need to set up your development environment. Here's what you need:

Prerequisites

  • Node.js: Make sure you have Node.js installed. You can download it from the official website.
  • TypeScript: Install TypeScript globally using npm:

bash npm install -g typescript

  • Express.js: You will also need to install Express:

bash npm install express

  • Type Definitions: For TypeScript to understand Express, you’ll need the type definitions:

bash npm install --save-dev @types/express

Project Structure

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

mkdir express-typescript-api
cd express-typescript-api

Then, initialize a new Node.js project:

npm init -y

Now, create the following folder structure:

express-typescript-api/
├── src/
│   ├── controllers/
│   ├── models/
│   ├── routes/
│   └── app.ts
└── tsconfig.json

tsconfig.json

Create a tsconfig.json file in the root directory with the following content:

{
  "compilerOptions": {
    "target": "ES6",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "outDir": "./dist"
  },
  "include": ["src/**/*"]
}

Writing Your First RESTful API

Now, let’s start coding! We will create a simple API for managing a list of users.

Step 1: Create the User Model

Inside the models folder, create a file named User.ts:

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

Step 2: Create the User Controller

Next, create a file named userController.ts in the controllers folder:

import { Request, Response } from 'express';
import { User } from '../models/User';

let users: User[] = [
  { id: 1, name: 'John Doe', email: 'john@example.com' },
  { id: 2, name: 'Jane Doe', email: 'jane@example.com' },
];

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

export const addUser = (req: Request, res: Response) => {
  const newUser: User = req.body;
  users.push(newUser);
  res.status(201).json(newUser);
};

Step 3: Create the User Routes

In the routes folder, create a file named userRoutes.ts:

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

const router = Router();

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

export default router;

Step 4: Set Up the Express Application

In the app.ts file, set up the Express server and configure routes:

import express from 'express';
import bodyParser from 'body-parser';
import userRoutes from './routes/userRoutes';

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

// Middleware
app.use(bodyParser.json());

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

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

Step 5: Running the Application

Before you run your application, install body-parser:

npm install body-parser

Now, you can compile your TypeScript code and run the server:

tsc
node dist/app.js

Testing Your API

You can test your API using tools like Postman or cURL.

  • Get Users: Send a GET request to http://localhost:3000/api/users.
  • Add User: Send a POST request with a JSON body to http://localhost:3000/api/users:
{
  "id": 3,
  "name": "Sam Smith",
  "email": "sam@example.com"
}

Troubleshooting Tips

  • Type Errors: Ensure that your TypeScript types are correctly defined and imported.
  • Server Not Starting: Check your console for any errors related to package imports or server configuration.
  • API Not Responding: Verify that your routes are correctly set and that you are hitting the right endpoints.

Conclusion

Building a RESTful API with Express.js and TypeScript can significantly enhance your web applications by providing a structured way for different systems to communicate. By following the steps outlined in this article, you now have a foundational understanding of how to create a simple but functional API.

Feel free to expand upon this base by adding features like authentication, database integration, and error handling to create a more robust application. Happy coding!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.