How to use TypeScript to build Node.js API with Express ?
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.
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.
- 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.
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.
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.
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.
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.
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.
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.