A Beginner's Guide to Building RESTful APIs with TypeScript and Express
Learn how to build a simple RESTful API using TypeScript and Express, perfect for beginners who want to start backend development with modern tools.
Building RESTful APIs is a fundamental skill for backend development. In this tutorial, we'll learn how to set up a simple RESTful API using TypeScript and Express. TypeScript adds type safety and better developer experience over plain JavaScript, making our code more reliable and easier to maintain.
Before we start, make sure you have Node.js and npm installed on your computer. You can download it from the official Node.js website.
Let's begin by creating a new project folder and initializing it with npm:
mkdir typescript-express-api
cd typescript-express-api
npm init -yNext, install the necessary dependencies. We'll need Express for the web server, TypeScript for typing, and some types packages for better TypeScript integration.
npm install express
npm install --save-dev typescript @types/node @types/express ts-node nodemonNow, create a `tsconfig.json` file to configure TypeScript by running:
npx tsc --initOpen the `tsconfig.json` file and make sure the following options are set or add them if missing to enable modern JavaScript features and support for modules:
{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"outDir": "dist",
"rootDir": "src",
"strict": true,
"esModuleInterop": true
}
}Next, create a new folder named `src` and inside it, create a file called `index.ts`. This will be the entry point of our API.
Let's write some basic Express server code in `src/index.ts`:
import express, { Request, Response } from 'express';
const app = express();
const port = 3000;
// Use JSON middleware to parse JSON bodies
app.use(express.json());
// A simple GET route
app.get('/', (req: Request, res: Response) => {
res.send('Hello from TypeScript and Express!');
});
// Start the server
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});To run the server easily during development, add a start script to your `package.json` like this:
"scripts": {
"start": "nodemon --exec ts-node src/index.ts"
}Now run the server with:
npm startVisit `http://localhost:3000` in your browser or use a tool like Postman to see the greeting message.
### Adding a RESTful Resource
Let's add a simple resource: a list of books. We'll create routes to GET all books, GET a book by ID, POST a new book, PUT to update a book, and DELETE a book.
First, define a Book type for TypeScript:
type Book = {
id: number;
title: string;
author: string;
};Create an in-memory array to act as our database:
let books: Book[] = [
{ id: 1, title: '1984', author: 'George Orwell' },
{ id: 2, title: 'To Kill a Mockingbird', author: 'Harper Lee' }
];Add the routes for the CRUD operations:
// GET all books
app.get('/books', (req: Request, res: Response) => {
res.json(books);
});
// GET a book by ID
app.get('/books/:id', (req: Request, res: Response) => {
const id = parseInt(req.params.id);
const book = books.find(b => b.id === id);
if (book) {
res.json(book);
} else {
res.status(404).json({ message: 'Book not found' });
}
});
// POST a new book
app.post('/books', (req: Request, res: Response) => {
const { title, author } = req.body;
if (!title || !author) {
res.status(400).json({ message: 'Title and author are required' });
return;
}
const newBook: Book = {
id: books.length > 0 ? books[books.length - 1].id + 1 : 1,
title,
author
};
books.push(newBook);
res.status(201).json(newBook);
});
// PUT update a book
app.put('/books/:id', (req: Request, res: Response) => {
const id = parseInt(req.params.id);
const { title, author } = req.body;
const bookIndex = books.findIndex(b => b.id === id);
if (bookIndex === -1) {
res.status(404).json({ message: 'Book not found' });
return;
}
if (!title || !author) {
res.status(400).json({ message: 'Title and author are required' });
return;
}
books[bookIndex] = { id, title, author };
res.json(books[bookIndex]);
});
// DELETE a book
app.delete('/books/:id', (req: Request, res: Response) => {
const id = parseInt(req.params.id);
const bookIndex = books.findIndex(b => b.id === id);
if (bookIndex === -1) {
res.status(404).json({ message: 'Book not found' });
return;
}
books.splice(bookIndex, 1);
res.status(204).send();
});This completes a simple RESTful API to manage books. You can test these routes using tools like Postman or curl.
### Conclusion
In this tutorial, you learned how to build a basic RESTful API using TypeScript and Express. This foundation can be expanded with real databases, authentication, validation, and other backend features. Using TypeScript helps catch errors early and makes your code easier to understand.
Keep practicing, and happy coding!