Simple REST API with TypeScript
I replicated Simple REST API with Go with TypeScript. It produced the same response. A single file and the code are almost similar. We can use the same Postman collection to try this one.
Before we get started, feel free to visit JavaScript Crash Course and TypeScript Crash Course. No basics of JavaScript and TypeScript here.
Prerequisites
- We will run the
index.js
by Nodemon while compilingindex.ts
. It watches changes. I suggest installing Nodemon globally because it is only for development. -
Create a
package.json
and set these scripts.1 2 3 4 5 6 7 8 9
{ ... "scripts": { "build": "tsc", "start": "node index.js", "dev": "tsc --watch & nodemon index.js" }, ... }
- The
build
is for compilingindex.ts
toindex.js
. - The
start
is for running the app in the production. - The
dev
is for compiling theindex.ts
file and running theindex.js
file by Nodemon.
- The
- Create a standard
tsconfig.json
file bytsc --init
. -
Install Express.
npm install express
oryarn add express
.npm install -D @types/express
oryarn add @types/express -D
. The@types
is for Type Declarations. They are for type-checking.-D
or--save-dev
means the package will appear indevDependencies
.
index.ts
Create an index.ts
file. We only need a single file.
|
|
- We can import
Express
,Request
, andResponse
fromexpress
as type. - We defined
port
,version
, andpath
as constants. You can change them by environment variables if you want. - We created initial articles.
- The
app.use(express.json())
makes us can read JSON body.
Let's add some functions below.
Index
|
|
We converted Map to Object and then print it as JSON.
Create
|
|
Incremented the ID and then set it to the map.
Read
|
|
Returns 404 if the article with that ID doesn't exist.
Replace
|
|
We overwrote the map.
Modify
|
|
We overwrote the attribute if the data exists.
Remove
|
|
We deleted the entry from the map and then returned Status OK.
Closing
|
|
The produced response could be like the example above. Maybe it is not a best practice of REST API. For example, the response for the Index should be an array of articles, not an object like the above. That is because I didn't use any database and stored the data on the map. At least we got the points. We replicated our previous code from GoLang to TypeScript.
Using TypeScript instead of JavaScript for development is beneficial. Even for back-end development too. Because TypeScript is strict. This article is an example of that. You can clone this example at https://github.com/aristorinjuang/ts-rest-api.
Related Articles
- TypeScript Crash Course
- JavaScript Crash Course
- React with TypeScript
- Cracking SQL Interview
- jQuery Semantic Tabs