Skip to content
Related Articles

Related Articles

Improve Article

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

  • Difficulty Level : Expert
  • Last Updated : 06 Oct, 2021

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.

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 endpints.
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 formate. 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.



index.js

Javascript




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

Step 4: The second API only shows the array data. In simple get request. Here we only return our dummy database as a JSON format.

index.js




// Handle '/users', path for fatch users.
app.get('/users', (_req, _res): void => {
    _res.json({
        "success": true,
        "users": fake_db 
    });
})

Step to run the application: After creating both API navigate the index.ts path and run the server using the below command on the terminal.

npm start

Final Codebase: All the above code is just to show how to create the route and this is the final index.js file that contains all the above code discussed.

index.js




// 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 are 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'
    });
});
  
// A globle Object treat as a fake database
let fake_db: any = [];
  
// Handle '/create', path for create user
app.post('/create', (_req, _res): void => {
  
    // Fatched the user using body data
    const user: object = _req.body;
  
    // Asigen the user in fake_db with
    // id as a index
    fake_db.push(user);
  
    _res.json({
        "success": true,
        "data": user
    });
});
  
// Handle '/users', path for fatch users
app.get('/users', (_req, _res): void => {
    _res.json({
        "success": true,
        "users": fake_db
    });
})
  
// Serve the api endpints
app.listen(port, (): void => {
    console.log(
`Typescript API server http://localhost:${port}/`);
});

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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :