TypeScript / TypeScript with Node.js

Building a REST API with TypeScript and Express

In this tutorial, you will learn how to build a RESTful API using TypeScript and Express.js. You will define routes, handle requests, and send responses.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Explains integrating TypeScript with Node.js and building backend applications with TypeScript.

Building a REST API with TypeScript and Express

1. Introduction

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.

2. Step-by-Step Guide

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.

3. Code Examples

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.

4. Summary

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.

5. Practice Exercises

  1. Create a PUT route at /users/:id that updates a user.
  2. Add error handling to the DELETE route from the example above. If the user tries to delete a user that doesn't exist, return a 404 status code and a helpful error message.
  3. (Advanced) Integrate a database (like SQLite, MongoDB, or PostgreSQL) to persist user data across server restarts.

Remember to test your routes using a tool like Postman or curl. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Base64 Encoder/Decoder

Encode and decode Base64 strings.

Use tool

Favicon Generator

Create favicons from images.

Use tool

Image Compressor

Reduce image file sizes while maintaining quality.

Use tool

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

MD5/SHA Hash Generator

Generate MD5, SHA-1, SHA-256, or SHA-512 hashes.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help