Table of Contents
TypeScript has become a popular choice for building scalable and maintainable server-side applications. Its strong typing and modern JavaScript features make it ideal for developing REST APIs. In this article, we will explore how to create a REST API using Express and TypeScript, with practical examples to guide you through the process.
Setting Up the Project
Begin by initializing a new Node.js project and installing the necessary dependencies. Use npm or yarn to set up your environment.
- Initialize the project:
npm init -y - Install Express, TypeScript, and types:
npm install express - Install dev dependencies:
npm install -D typescript @types/node @types/express - Create a
tsconfig.jsonfile for TypeScript configuration.
Configure tsconfig.json with appropriate settings for Node.js development.
Creating the Server
Set up a basic Express server in TypeScript. Create a file named index.ts and add the following code:
import express from 'express';
const app = express();
const port = 3000;
app.use(express.json());
app.get('/', (req, res) => {
res.send('Hello, TypeScript REST API!');
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
Building CRUD Endpoints
Implement CRUD (Create, Read, Update, Delete) operations for a resource, such as "items". Use in-memory data storage for simplicity.
interface Item {
id: number;
name: string;
}
let items: Item[] = [
{ id: 1, name: 'Item One' },
{ id: 2, name: 'Item Two' },
];
// Create
app.post('/items', (req, res) => {
const newItem: Item = {
id: Date.now(),
name: req.body.name,
};
items.push(newItem);
res.status(201).json(newItem);
});
// Read all
app.get('/items', (req, res) => {
res.json(items);
});
// Read one
app.get('/items/:id', (req, res) => {
const id = parseInt(req.params.id);
const item = items.find(i => i.id === id);
if (item) {
res.json(item);
} else {
res.status(404).json({ message: 'Item not found' });
}
});
// Update
app.put('/items/:id', (req, res) => {
const id = parseInt(req.params.id);
const index = items.findIndex(i => i.id === id);
if (index !== -1) {
items[index].name = req.body.name;
res.json(items[index]);
} else {
res.status(404).json({ message: 'Item not found' });
}
});
// Delete
app.delete('/items/:id', (req, res) => {
const id = parseInt(req.params.id);
items = items.filter(i => i.id !== id);
res.status(204).send();
});
Type Safety and Validation
Enhance your API with input validation and error handling. Use libraries like express-validator or custom middleware to ensure data integrity.
Example: Validating Input
import { body, validationResult } from 'express-validator';
app.post('/items',
body('name').isString().notEmpty(),
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const newItem: Item = {
id: Date.now(),
name: req.body.name,
};
items.push(newItem);
res.status(201).json(newItem);
}
);
Running and Testing the API
Compile your TypeScript code using tsc and start the server with node. Use tools like Postman or curl to test your endpoints.
Example curl command to fetch all items:
curl http://localhost:3000/items
With this setup, you can extend your API with additional features such as authentication, database integration, and more complex validation.
Conclusion
Building a REST API with TypeScript and Express provides a robust foundation for scalable backend development. By leveraging TypeScript's type safety and Express's simplicity, developers can create maintainable and efficient APIs suitable for various applications.