How to Build REST APIs With Express and TypeScript

How to Build REST APIs With Express and TypeScript

Building REST APIs with Express and TypeScript is an effective way to create scalable and maintainable server-side applications. TypeScript, a superset of JavaScript, provides static typing and other features that enhance the development experience. Below are the steps to create a simple REST API using these technologies.

Step 1: Setup Your Development Environment

To get started, ensure you have Node.js and npm (Node Package Manager) installed on your machine. You can download them from the official Node.js website.

Once Node.js is installed, create a new directory for your project and navigate to it:

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

Next, initialize a new npm project:

npm init -y

Step 2: Install Required Packages

Install Express and TypeScript as well as the required type definitions:

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

To enable type-checking and compilation for TypeScript, you must create a tsconfig.json file. You can run the following command:

npx tsc --init

Step 3: Configure TypeScript

Edit your tsconfig.json file to include the following settings for a basic Express application:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "outDir": "./dist"
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "**/*.spec.ts"]
}

Step 4: Create Your Project Structure

Organize your files by creating a src directory:

mkdir src

Within the src directory, create a new file index.ts:

touch src/index.ts

Step 5: Write Your Express Application

Open src/index.ts and write the following code:

import express, { Request, Response } from 'express';
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
app.get('/api', (req: Request, res: Response) => {
  res.send('Hello, World!');
});
app.get('/api/items', (req: Request, res: Response) => {
  const items = [
    { id: 1, name: 'Item 1' },
    { id: 2, name: 'Item 2' }
  ];
  res.json(items);
});
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Step 6: Compile and Run Your Application

To run your application, compile the TypeScript code and then start the server. You can do this using:

npx tsc
node dist/index.js

Alternatively, to run your application in development mode without compiling each time, use:

npx ts-node src/index.ts

Step 7: Test Your API

Now that your API is up and running, you can test it using a tool like Postman or simply your web browser. Navigate to http://localhost:3000/api to see the "Hello, World!" message, or http://localhost:3000/api/items to view the items.

Conclusion

Building REST APIs with Express and TypeScript allows for a modern and efficient approach to backend development. By following these steps, you have created a simple API that can serve as a foundation for more complex applications. With TypeScript's type system, you can greatly enhance code quality and reduce runtime errors.