DEV Community

Cover image for Introduction to TypeScript with Express: Building Your First REST API
FredAbod
FredAbod

Posted on • Edited on

1

Introduction to TypeScript with Express: Building Your First REST API

Introduction to TypeScript with Express: Building Your First REST API

Are you ready to dive into the world of TypeScript and build a simple REST API using Express😊? Whether you're new to TypeScript or just want to get hands-on with backend development, this tutorial is for you! fire up your code editor, and let's get started.

Let's Dive IN

Dive In


Ok so what's TypeScript?

TypeScript is like JavaScript with superpowers. It's a superset of JavaScript that adds optional static typing, making your code more predictable and less prone to bugs. Think of it as having a safety net while you code!

Okay Okay what about Express🤔🤔??

Express is a fast and lightweight web framework for Node.js. It's like the glue that helps you build web servers and APIs effortlessly.

If you've not used Typescript before on your machine do this npm install -g typescript

Now let's Build A Very Simple User API

Step 1: Setting Up Your Project

run this cmds

mkdir typescript-express-tutorial
cd typescript-express-tutorial
npm init -y
Enter fullscreen mode Exit fullscreen mode

Step 2: Lets Install The Necessary Dependencies

run this😉😉😉

npm install express
npm install --save-dev typescript @types/express ts-node
Enter fullscreen mode Exit fullscreen mode

Soooooooooooo

  • express: The web framework.

  • typescript: Our TypeScript compiler.

  • @types/express: Type definitions for Express.

  • ts-node: Allows us to run TypeScript files directly.

Step 3: Configure TypeScript

Run The Command:
tsc --init

Step 4: Let's configure our tsconfig.json file and also our scripts in package.json

in tsconfig.json add

    "rootDir": "./src",  
    "outDir": "./dist",   
Enter fullscreen mode Exit fullscreen mode

in package.json change your scripts too

  "scripts": {
    "start": "node dist/server.js",
    "dev": "ts-node-dev src/server.ts",
    "build": "tsc"
  },
Enter fullscreen mode Exit fullscreen mode

Step 5: Create the Folder And File

mkdir src
touch src/index.ts
Enter fullscreen mode Exit fullscreen mode

we're almost there

Almost There

Step 6: The Code Body for index.ts

import express, { Request, Response } from 'express';

const app = express();
const port = 3000;

app.use(express.json());

app.get('/', (req: Request, res: Response) => {
    res.send('Hello, TypeScript API!');
});

app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
});
Enter fullscreen mode Exit fullscreen mode

Step 7: Now we add Static Typing

interface User {
    id: number;
    name: string;
    email: string;
}
Enter fullscreen mode Exit fullscreen mode

We then use this types in our API

const users: User[] = [
    { id: 1, name: 'Alice', email: 'alice@example.com' },
    { id: 2, name: 'Bob', email: 'bob@example.com' },
];

app.get('/users', (req: Request, res: Response) => {
    res.json(users);
});
Enter fullscreen mode Exit fullscreen mode

Your Final Code should look like this

import express, { Request, Response } from 'express';

const app = express();
const port = 3000;

app.use(express.json());

interface User {
    id: number;
    name: string;
    email: string;
}

const users: User[] = [
    { id: 1, name: "John", email: "alice@gmail.com" },
    { id: 2, name: "Alice", email: "bob@gmail" },
];

app.get('/', (req: Request, res: Response) => {
    res.send("Hello, world!");
});

app.get('/users', (req: Request, res: Response) => {
    res.json(users);
});

app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});
Enter fullscreen mode Exit fullscreen mode

And Wala You're done the simplest and easiest start you can have with TYPESCRIPT

Now to test

npx ts-node-dev src/index.ts

And that's It

Follow me for more Articles like this
as I'll be talking and doing a lot of projects with typescript in the coming week don't forget to drop a like❤️❤️❤️

The END

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay