Open In App

How to use TypeScript to build Node.js API with Express ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to create an Express Route and API in TypeScript and help us with the default type checking mechanism. And we will create some Fake API endpoints with the help of TypeScript with ExpressJS configuration and understand how to use TypeScript in our ExpressJS project.

TypeScript is a superset of JavaScript with some additional features that JavaScript doesn’t have such as type notation and static type changing or using es6’s code in older codebases. Typescript provides all the features. If you want to create an API service in typescript use of express with NodeJS, you must first set up your project with typescript. If you have no idea about how to set up express in typescript refer to this article.

I hope you have set up your express project with typescript using the above article now we will start to create our first API in Typescript. 

Prerequisites:

  • Basic knowledge about NodeJs.
  • Basic knowledge about Express Js and their routes management techniques.
  • Basic knowledge about TypeScript and its uses.

Approach:  Setup directory Structure according to the above-mentioned article. Initiate ExpressJs with TypeScript. Will create two fake API to create a user and get user data with ExpressJs TypeScript configuration. See the final codebase file. Will test our API endpoints with the help of the Postman API Testing Tool and see our API output.

Step 1: If you are set up the project in the use of the above article your directory looks like this.

Step 2: Open the index.ts file and write the below code. First of all, create an ExpressJs code in TypeScript and flow the good practices.

Filename: index.js 

Javascript




// Import the express with express name
import express from 'express';
 
// Initialize the express module with app variable
const app: express.Application = express();
 
// Define the port for the application is run
const port: number = 3000;
 
// Handle the coming data.
app.use(express.json());
 
// Handle '/', path of the api.
app.get('/', (_req, _res): void => {
    _res.json({
        'name': 'typescitp_api',
        'path': '/',
        'work': 'search_other_apis'
    });
});
 
 
// Server the api endpoints.
app.listen(port, (): void => {
    console.log(`Typescript API server http://localhost:${port}/`);
});


 
Step 3: In this step, we create two API endpoints for creating the user and getting the users’ data. Firstly create a global array to treat as a fake database.

Syntax: 

let fake_db: any = [];

Then create a first API endpoint to create the users and store the user data in the fake database. We are working with API endpoint so data are passed through the post method or JSON data format. In the below code, we firstly handle a post request and create a  ‘/create’ route the manage or create user API endpoint and after that assign the coming body data to our fake database and return appropriate output.

Filename: index.js

Javascript




// Handle '/create', path for create user
app.post('/create', (_req, _res): void => {
 
    // Fetched the user using body data
    const user: object = _req.body;
 
    // Assign the user in fake_db with id as a index
    fake_db.push(user);
 
    _res.json({
        "success": true,
        "data": user
    });
});


After writing all codes lets, move to the test phase and look at what our API makes output.

Step 5: Now the final step is to test all the created routes using Postman. If you don’t know about the postman refer to this article.

1. Test ‘/’ root path using postman.

The root path working properly, so we are moving to another API endpoint.

2. Test ‘/create’ path in post request using postman.

We pass raw JSON data directly.

3. Test ‘/users’ path using postman.



Last Updated : 23 Jan, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads