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.jsby Nodemon while compilingindex.ts. It watches changes. I suggest installing Nodemon globally because it is only for development. -
Create a
package.jsonand 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
buildis for compilingindex.tstoindex.js. - The
startis for running the app in the production. - The
devis for compiling theindex.tsfile and running theindex.jsfile by Nodemon.
- The
- Create a standard
tsconfig.jsonfile bytsc --init. -
Install Express.
npm install expressoryarn add express.npm install -D @types/expressoryarn add @types/express -D. The@typesis for Type Declarations. They are for type-checking.-Dor--save-devmeans the package will appear indevDependencies.
index.ts
Create an index.ts file. We only need a single file.
|
|
- We can import
Express,Request, andResponsefromexpressas type. - We defined
port,version, andpathas 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