How to Build REST API with TypeScript using only native modules

is a typed superset of JavaScript that compiles to plain JavaScript during runtime. The dynamic nature of JavaScript does not allow you to catch any unexpected results unless the program has been executed, so the TypeScript type system will enable you to catch such errors at compile time instead of runtime. This means that any valid JavaScript code is also equivalent and valid TypeScript code.

TypeScript is both a language and a set of tools. As a language, it comprises syntax, keywords, and . Its toolset provides type information that the IDE can use to supply autocompletion, type hinting, refactoring options, static typing, and other features.

The TypeScript and JavaScript ecosystem offers diverse tools and libraries that help you build your application faster. For example, you will probably use the library to set up your API when creating a server. Express provides you with functions to set up and manage your HTTP server at scale.

However, these libraries are developed using vanilla JavaScript. Behind the scenes, your Express server runs on raw TypeScript or JavaScript. This means the functions and methods that Express provides abstract the low-level logic of the vanilla base language. Your server does not directly interact with the base logic that the TypeScript or JavaScript provides; instead, Express accesses the vanilla code and transforms it to scalable code that lets you reduce your codebase.

Using these libraries speeds up your development time while reducing redundant code; the advantage they provide is undisputed. However, you might want to leverage the “bare bones” of TypeScript and run your apps using the vanilla code. This will help you execute the purest server without using libraries such as Express.

This guide will demonstrate how to use TypeScript to create a REST API using only the native modules. The project aims to help you learn how to make an HTTP server in Node.js without using additional libraries.

How to set up TypeScript with Node.js

This tutorial will use Node to run TypeScript. Node is a JavaScript runtime designed to create scalable asynchronous event-driven applications.

Go ahead and install on your computer. Then, create a project folder and initialize your project using npm init -y.

Let’s configure Node to run TypeScript code. You need TypeScript dependencies available for Node. To do so, install the TypeScript Node package using the following command:

npm install -D typescript

You can now utilize your TypeScript project using tsc --init. This will create a tsconfig.json file with the default TypeScript compile options.

While running the TypeScript code, you need to execute the above dependencies using a Node command. To do this, use a TypeScript execution engine and REPL library called . Ts-node allows you to run a one-time command that points to .ts files, compile and run them on the browser.

Go ahead and install ts-node like so:

npm install -D ts-node 

Then, edit your package.json script tags:

"scripts": {"start": "ts-node ./src/index.ts"},

This means ts-node will point the /src/index.ts file as the main file and execute the .ts code and modules that index.ts points to.

Finally, add a @types/node library to your project. Node runs on JavaScript, and this project uses TypeScript. Thus, you need to add type definitions for Node to run TypeScript.

contains built-in TypeScript definitions. To install it, run:

npm install @types/node

How to create a simple TypeScript HTTP server

The TypeScript Node setup is ready to run your code. Let’s see how to create a basic HTTP server that runs using the HTTP native module.

First, create an src folder and add an index.ts file. Then, set up a basic TypeScript HTTP server using Node with the following steps.

To begin, import the HTTP native module:

import HTTP from "HTTP";

To create an HTTP server and client, you need to use the HTTP command from "http". This will allow you to have the necessary functions to create a server.

Next, create a local server from which to receive data:

const myServer = http.createServer((req, res) => { res.write('Hello World!') res.end()});

Set up a server instance using the createServer() function. This function allows you to issue HTTP requests and responses. The res.write code allows you to specify the incoming message that the server should execute. res.end() ends the set incoming requests even when no data is written to the body of the request or sent by the HTTP response.

Then, start the server and listen for connections:

myServer.listen(3000, () => { console.log('Server is running on port 3000. Go to http://localhost:3000/')}); myServer.close()

listen() will create a localhost TCP server listening on port 3000. In this case, 3000 must be the unused port that the server will be immediately get assigned to once it starts listening for connections. The listen() method is asynchronous, and manages how the server accepts new connections while exiting the current ones. When all connections have ended, the server is asynchronously closed. If an error occurs, the server will be called with an Error and closed immediately.

Once you run your app using npm start, the server will start, and you can access it on . The Hello World! message specified in the response body will be served on your browser. This basic HTTP API is very low-level and runs on the most basic of TypeScript.

How to create a CRUD TypeScript REST API

The above example only used the HTTP module to set a basic server. Let’s dive in and build a REST API that uses the CRUD (create, read, update, and delete) methods.

To set up this API, start by storing our sample to-do list in a JSON file. Then, create a store.json file inside the src folder and add the following list of tasks:

[{"id": 1,"title": "Learn React","completed": false},{"id": 2,"title": "Learn Redux","completed": false},{"id": 3,"title": "Learn React Router","completed": false},{"id": 4,"title": "Cooking Lunch","completed": true}]

The to-do list API will refer to this data to perform server-based methods like GET, POST, PUT, and DELETE.

Leave A Replay