Introduction: Why TypeScript for REST API?
Modern web development is unthinkable without creating efficient and secure APIs. TypeScript, as a superset of JavaScript, offers static typing, which significantly reduces the number of runtime errors and improves code readability. In this guide, we will show you how to write a full-fledged REST API in TypeScript in just 30 minutes. You will learn how to set up a project, create basic endpoints, and handle errors. This tutorial is perfect for beginner developers who want to quickly master building server-side applications.
Environment Setup and Dependency Installation
First, you need to create a new project and install all the necessary packages. Make sure you have Node.js (version 18 or higher) and npm installed.
Step 1: Project Initialization
Open a terminal and run the following commands:
mkdir my-rest-apicd my-rest-apinpm init -yStep 2: Installing TypeScript and Dependencies
Install TypeScript, Express, and the necessary types:
npm install expressnpm install -D typescript @types/node @types/express ts-node nodemon- express — framework for creating a server.
- typescript — TypeScript compiler.
- @types/express — types for Express.
- ts-node — for running TypeScript directly.
- nodemon — automatic server restart on changes.
Step 3: Configuring tsconfig.json
Create a tsconfig.json file in the project root:
{ "compilerOptions": { "target": "ES2020", "module": "commonjs", "outDir": "./dist", "rootDir": "./src", "strict": true, "esModuleInterop": true, "skipLibCheck": true }, "include": ["src/**/*"], "exclude": ["node_modules"]}Creating a Basic Server in TypeScript
Now let's create the folder structure and the main server file.
Step 4: Project Structure
Create a src folder and a src/index.ts file:
mkdir srctouch src/index.tsStep 5: Writing the Server
Open src/index.ts and add the following code:
import express, { Request, Response } from 'express';
const app = express();const PORT = process.env.PORT || 3000;
// Middleware for parsing JSONapp.use(express.json());
// Basic routeapp.get('/', (req: Request, res: Response) => { res.send('REST API on TypeScript is working!');});
// Start the serverapp.listen(PORT, () => { console.log(`Server running on port ${PORT}`);});Step 6: Adding Scripts to package.json
Update package.json by adding scripts for development and build:
"scripts": { "dev": "nodemon --exec ts-node src/index.ts", "build": "tsc", "start": "node dist/index.js"}Now start the server with the command npm run dev. You should see the message "Server running on port 3000".
Implementing CRUD Endpoints
Let's create a simple data model and implement Create, Read, Update, and Delete (CRUD) operations. For the example, we'll use the "Task" entity.
Step 7: Creating the Model and Storage
Create a file src/models/Task.ts:
export interface Task { id: number; title: string; completed: boolean;}
// Temporary in-memory storageexport const tasks: Task[] = [ { id: 1, title: 'Learn TypeScript', completed: false }, { id: 2, title: 'Write REST API', completed: false },];Step 8: Creating Routes
Create a file src/routes/tasks.ts:
import { Router, Request, Response } from