How to build A TypeScript + Express API in a Nodejs Environment

Chiboy
8 min readJun 17, 2024

Hi there! I hope you’re having a wonderful day and enjoying your coding adventure.

In this session of our TypeScript series we will be discussing on how to create an API in TypeScript using express package in Nodejs, while doing this we will also learn the concept of installing packages in Nodejs and TypeScript.

WHAT IS AN API

An API, or Application Programming Interface, is a way for different software applications to communicate with each other. Think of it as a set of rules or protocols that allows one program to send requests to another program and get responses back.

Simple Explanation:

Imagine you are at a restaurant. You (the customer) sit at a table with a menu of dishes to choose from. The kitchen (the system) is part of the restaurant that will prepare your order. You need a way to communicate your order to the kitchen and then get the food back to your table. This is where the waiter (the API) comes in.

Lets get started with coding ….

  1. Lets create our project folder, open your terminal and paste this command
mkdir typescript_tut

This will create a folder called typescript_tut

2. Now navigate to the project with this command:

cd typescript_tut

3. Next, lets initialize node in our project, open your project in your favorite IDE and run this command on the terminal:

npm init --y

This will initialize the newly created project with Node and create a new file package.json

4. Lets also initialize TypeScript into the project by running this command:

tsc --init

This will create a tsconfig.json file for the TypeScript configurations

NOTE: when creating a Typescript file, the extension is .ts

5. Next, lets configure the TypeScript project. Go to the tsconfig.json and adjust/edit it to look like this:

{
"compilerOptions": {
"target": "ES2022", /* Specify ECMAScript target version */
"module": "commonjs", /* Specify module code generation */
"rootDir": "./src", /* Specify the root directory of input files */
"outDir": "./dist", /* Redirect output structure to the directory */
"strict": true, /* Enable all strict type-checking options */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules */
"skipLibCheck": true /* Skip type checking of all declaration files (*.d.ts) */
}
}

Note: This setup provides basic configuration, but you can still customize it according to your project specifications.

6. We will also configure the package.json files, so inside the script object add this command:

"start": "tsc && node dist/index.js"

So, what this does is, when you run your application it first compiles the typescript then run the JavaScript application

NOTE: tsc command compiles the TypeScript code to JavaScript and then output the result

7. Next, we will create a folder src and then create a file inside it called index.ts

8. Now, we will install dependencies that are necessary for our project, paste this command in terminal:

npm install @types/node @types/express express body-parser @types/body-parser 
  • @types/express: Provides TypeScript type definitions for Express, allowing for type-safe usage of Express.js in TypeScript applications.
  • express: A minimalist web framework for Node.js, used for building web and mobile applications.

9. Next, lets create our simple server for running express by importing the express module. So paste this code inside the index.ts file we created:

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

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


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


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

So this has created a simple server with a single GET method endpoint.

10. Next, to run our application, we need to compile the TypeScript code to JavaScript.
So by default browsers don’t run TypeScript files directly, they only understand JavaScript. So therefore we will need to compile the TypeScript to JavaScript.
Run this command:

npm start

This will start our application and ready to access endpoints within

NOTE: The configuration we did in package.json file will be responsible for compiling TypeScript to JavaScript

11. Next, lets test the API endpoint available in our project which is running on port: 3000. Open your browser and enter this Url in the address bar:

http://localhost:3000/

By doing this, your browser is supposed to return with a response like this:

Create a simple CRUD application

Now we have successfully created a working server. So lets move forward with creating a more robust API for Students so that we can explore other API request method for CRUD operation (CREATE, READ, UPDATE & DELETE)

We will be creating an API that manages student data

  1. In your src folder, create a folder model then create a file students.ts . Add the following code inside it
export interface Students {
id: number;
name: string;
schoolName: string;
class: string;
}

Here we made use of TypeScript Interface to define the students schema or data structure.

2. Next, In your src folder, create a folder routes then create a file students.ts . Add the following code inside it

import { Router, Request, Response } from 'express';
import { Students } from '../model/students';

const router = Router();
let students: Students[] = [];

// Add your CRUD API implementation here

// Add student
router.post('/add', (req: Request, res: Response) => {
const student: Students = {
id: students.length + 1,
name: req.body.name,
schoolName: req.body.schoolName,
class: req.body.class
}
students.push(student);
res.status(201).json(student);
})

// Get student

// Update Student

// Delete Student

export default router;

So in this part we imported express and students module we created earlier, then we created a POST endpoint that add students into te student array.

3. Now, Go to your index.ts file and make this modification just like the following code:

import express, { Request, Response } from 'express';
import studentRoutes from './routes/students';
import bodyParser from 'body-parser';

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

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(express.json());
app.use('/api', studentRoutes);


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


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

So in this file index.ts we have modified it with importing our router module, body-parser module which enables pass request as json from the client side.

4. Now let us test the POST endpoint we just created for adding students data into the studentarray. For the purpose of this tutorial we will be making use of POSTMAN for testing our API.

NOTE: POSTMAN is an API(application programming interface) development tool that helps to build, test and modify APIs.

Run your project with the command npm start and ensure your TypeScript is compiling to JavaScript then head to your POSTMAN and use this url and sample request:

// API endpoint
POST: http://localhost:3000/api/add


// Sample request
{
"name": "Chiboy BadGuy",
"schoolName": "NMS",
"class": "ss2"
}


// Sample response
{
"id": 1,
"name": "Chiboy BadGuy",
"schoolName": "NMS",
"class": "ss2"
}
This is how the request looks on POSTMAN

Now we have successfully added a student with our POST endpoint

5. Next let us create an endpoint that fetches the students we added into the array. Go to the routes/students.ts file where we created the POST endpoint, then add the following code:

// routes/students.ts

// Get student
router.get("/get", (req: Request, res: Response) => {
if(students.length >= 1) {
res.status(200).json(students)
} else {
res.status(200).json("no result available")
}
})

// Update Student

// Delete Student

So basically, this is a GET method endpoint that checks if the student array is empty, if it’s not then it returns the result in the array.

6. Next, use this command npm start to compile the TypeScript file to JavaScript

7. Lets test to fetch the students record from the GET method we just created. Go to POSTMAN and run the url:

// API endpoint
GET: http://localhost:3000/api/get

// Sample response

[
{
"id": 1,
"name": "Chiboy BadGuy",
"schoolName": "NMS",
"class": "ss2"
},
{
"id": 2,
"name": "Ghosty GoodGuy",
"schoolName": "Google-sec-sch",
"class": "ss1"
}
]
This is how the request looks on POSTMAN

NOTE: As this is just for teaching purpose, we are using a temporary data storage which is an array, so therefore, anytime you restart or compile your project you we will be losing the previous record, though have it that it is still the same concept when it comes to storing real data

So by doing this we have been able to CREATE AND READ from our API, simple right 😋😎

8. Moving forward, lets create our API that UPDATES already existing students record. Add the following code into the routes/students.ts file where we created the GET endpoint:

// routes/students.ts

// Update Student
router.put('/update/:id', (req: Request, res: Response) => {
let student = students.find((x) => x.id === parseInt(req.params.id));

if (!student) {
res.status(404).json('Student not found');
} else {
student.name = req.body.name || student.name;
student.schoolName = req.body.schoolName || student.schoolName;
student.class = req.body.class || student.class;
}

res.status(201).json(student);
})

So basically, what this does is, it takes the id of the student we want to update as a req.param , we then do a find() array method to get the student details, in which if there’s no student with that id it returns a 404 status which indicates No student. Though if there’s a student you can assign the student with new values.

ASSIGNMENT: I won’t be testing this with you. Do it yourself (DIY) just like how we did CREATE and GET

9. Next, lets create our DELETE API that deletes a particular student by id
Add the following code into the routes/students.ts file where we created the PUT endpoint:

// routes/students.ts

// Delete Student
router.delete('/delete/:id', (req: Request, res: Response) => {
const index = students.findIndex((x) => x.id === parseInt(req.params.id));

if (index === -1) {
res.status(404).send('Student not found');
} else {
students.splice(index, 1);
res.status(202).json('Student successfully deleted');
}
});

This endpoint basically removes a particular student from the array by id

Conclusion

In this tutorial, we’ve successfully developed a Robust API using TypeScript and Express and also implemented CRUD operations for a Student data. By now you should have a great understanding on the concept of API creation on the server-side. Happy coding!

Show some love by ❤💛🧡💙❤
👏clap
💌subscribing
🚶‍♂️following

Thank you 🎉

--

--