In this tutorial, we aim to teach you how to build a RESTful API using TypeScript and Express.js. We'll cover defining routes, handling HTTP requests, and sending responses. By the end of this tutorial, you should have a basic understanding of how to construct a functional REST API using these tools.
What you will learn:
- Setting up a TypeScript project.
- Definition and usage of Express.js routes.
- How to handle HTTP requests and responses.
- Constructing a REST API from scratch.
Prerequisites:
- Basic knowledge of JavaScript and TypeScript.
- Node.js and npm installed on your local machine.
Firstly, let's set up a new TypeScript project. Initialize a new project using npm and install TypeScript, Express.js, and necessary types:
$ npm init -y
$ npm install express typescript ts-node
$ npm install @types/express --save-dev
$ npx tsc --init
Now, let's create a new index.ts
file in your project root. This will be the entry point to our application. Import express and create a simple server:
import express from 'express';
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
Run the server with the command npx ts-node index.ts
.
Now, let's create a RESTful route for managing a resource, for example, 'users'. Each user will have an id and a name:
// Define a new route for getting users
app.get('/users', (req, res) => {
const users = [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Smith' },
];
res.send(users);
});
You can now access the list of users by visiting http://localhost:3000/users
.
Example 1: Creating a POST route to add new users:
// First, let's add a middleware to parse JSON bodies
app.use(express.json());
// Define a new POST route for adding a user
app.post('/users', (req, res) => {
const newUser = req.body;
// In a real-world app, you'd save this user to a database here
res.status(201).send(newUser);
});
In this example, we used the express.json()
middleware to parse JSON request bodies. Then, we defined a POST route at '/users'. We simply echo back the received user in the response.
Example 2: Adding a DELETE route to remove a user:
// Define a new DELETE route for removing a user
app.delete('/users/:id', (req, res) => {
const { id } = req.params;
// In a real-world app, you'd delete this user from your database here
res.status(200).send(`User ${id} has been deleted`);
});
In this example, we define a DELETE route that takes an ID parameter. We then echo back a message confirming the deletion.
We've covered setting up a TypeScript project, defining routes in Express.js, handling HTTP requests, and sending responses.
For further learning, consider exploring how to integrate a database to persist data between server restarts, or look into more advanced Express.js topics like middleware and error handling.
/users/:id
that updates a user.Remember to test your routes using a tool like Postman or curl. Happy coding!