How To create an API using Node.js, Express, and Typescript

How To create an API using Node.js, Express, and Typescript

In this article, we will learn to create an API server using the Express framework and Typescript.

What is API?

An API (Application Programming Interface) is a way of interacting with a service, through a series of predefined requests.

Express

Express is an open-source web framework, for Node.js, designed to make developing websites, web apps, and API's easier.

Typescript

TypeScript is JavaScript with syntax for types, it is a strongly typed programming language that builds on JavaScript, giving you better tooling at any scale.

so let's dive into the tutorial,

Prerequisite:

  • Basic knowledge of NodeJs and Javascript
  • Basics of TypeScript

Step 1: Initialize the npm project

To initialize the project in the working directory and create a package.json file by running the below command in terminal

npm init -y

After running this command it will create the package.json file in the working directory

Step 2: Installing the dependencies

Now we have to install the required dependencies to create this API

npm install express dotenv

Dotenv - Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env

Now we need to install the dev dependencies for typescript support using --save-dev flag

npm install @types/node @types/express nodemon ts-node --save-dev

Now create a tsconfig.json file and save it with the below code

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "rootDir": "./",
    "outDir": "./build",
    "esModuleInterop": true,
    "strict": true
  }
}

Step 3: Add scripts in package.json file to run file

  "scripts": {
    "start": "ts-node server.ts",
    "dev": "nodemon --exec ts-node server.ts"
  },

Note - server.ts file which we will create in the next step

Step 4: Create a .env file

There are some details like port number, database URLs, username etc. which should be hidden and not to be exposed to public

so create a .env file and declare the port number

PORT=8080

Step 5: Create a server.ts file

Now comes an interesting part, creating server.ts file in root folder

first, we will import the packages

import Express from "express"
import dotenv from "dotenv"

Now get the port number from .env file

dotenv.config()
const PORT = process.env.PORT

Now the most important part, declaring '/' endpoint

const app : Express.Application = Express()

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

app.listen(PORT, () => {
    console.log(`Server is listening on ${PORT}`)
})

we define a / endpoint, that will return the text Hello World!, and run our application on port 8080.

Note that the / endpoint will only match for GET requests, as we've defined it using the app.get method.

Step 6: Running our API

In your terminal, run the following command to start the application:

npm run dev

if you see the output like below

➜  express-typescript npm run dev

> express-typescript@1.0.0 dev
> nodemon --exec ts-node server.ts

[nodemon] 2.0.14
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: ts,json
[nodemon] starting `ts-node server.ts`
Server is listening on 8080

Great! now open your browser and navigate to localhost:8080. If everything worked successfully, "Hello World" should be displayed in your browser.

Congratulations, You have created API using express and typeScript

Full code -

import Express from "express"
import dotenv from "dotenv"

dotenv.config()

const PORT = process.env.PORT

const app : Express.Application = Express()

app.get("/", (req: Express.Request, res: Express.Response) => {
    res.send("Hello worrld")
})

app.listen(PORT, () => {
    console.log(`Server is listening on ${PORT}`)
})

Loved the article? Follow me on - Twitter

Did you find this article valuable?

Support Nayan Patil by becoming a sponsor. Any amount is appreciated!