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

  1. We will run the index.js by Nodemon while compiling index.ts. It watches changes. I suggest installing Nodemon globally because it is only for development.
  2. 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 compiling index.ts to index.js.
    • The start is for running the app in the production.
    • The dev is for compiling the index.ts file and running the index.js file by Nodemon.
  3. Create a standard tsconfig.json file by tsc --init.
  4. Install Express.

    • npm install express or yarn add express.
    • npm install -D @types/express or yarn add @types/express -D. The @types is for Type Declarations. They are for type-checking. -D or --save-dev means the package will appear in devDependencies.

index.ts

Create an index.ts file. We only need a single file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import express, { Express, Request, Response } from 'express';

const app: Express = express();
const port: number = 80;
const version: string = '/v1';
const path: string = '/articles';

type article = {
  title: string
  description: string
}

var articles: Map<number, article> = new Map<number, article>([
  [1, {title: 'Simple REST API with TypeScript', description: "Let's create a simple REST API with TypeScript."}],
]);

app.use(express.json())

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
})

Let's add some functions below.

Index

1
2
3
app.get(version + path, (req: Request, res: Response) => {
  res.json(Object.fromEntries(articles));
})

We converted Map to Object and then print it as JSON.

Create

1
2
3
4
5
app.post(version + path, (req: Request, res: Response) => {
  let id: number = articles.size + 1
  articles.set(id, req.body)
  res.json({[id]: req.body});
})

Incremented the ID and then set it to the map.

Read

1
2
3
4
5
6
7
8
9
app.get(version + path + '/:id', (req: Request, res: Response) => {
  if (articles.get(Number(req.params.id)) === undefined) {
    res.status(404).end()

    return
  }

  res.json({[req.params.id]: articles.get(Number(req.params.id))});
})

Returns 404 if the article with that ID doesn't exist.

Replace

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
app.put(version + path + '/:id', (req: Request, res: Response) => {
  if (articles.get(Number(req.params.id)) === undefined) {
    res.status(404).end()

    return
  }

  articles.set(Number(req.params.id), req.body)
  res.json({[req.params.id]: articles.get(Number(req.params.id))});
})

We overwrote the map.

Modify

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
app.patch(version + path + '/:id', (req: Request, res: Response) => {
  let a = articles.get(Number(req.params.id));

  if (a === undefined) {
    res.status(404).end()

    return
  }

  a.title = req.body.title || a.title;
  a.description = req.body.description || a.description;

  articles.set(Number(req.params.id), a)

  res.json({[req.params.id]: a});
})

We overwrote the attribute if the data exists.

Remove

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
app.delete(version + path + '/:id', (req: Request, res: Response) => {
  if (articles.get(Number(req.params.id)) === undefined) {
    res.status(404).end()

    return
  }

  articles.delete(Number(req.params.id))
  res.status(200).end()
})

We deleted the entry from the map and then returned Status OK.

Closing

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
{
    "1": {
        "title": "Simple REST API with TypeScript",
        "description": "Let's create a simple REST API with TypeScript."
    },
    "2": {
        "title": "New Article",
        "description": "This is the new article that we have created."
    }
}

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