how to create api in typescript

To create an API in TypeScript, you can follow these steps:

  1. Install the TypeScript compiler by running npm install -g typescript in your terminal.
  2. Create a new Node.js project by running npm init and follow the prompts to set it up.
  3. Install the Express.js web framework by running npm install express.
  4. Create a new TypeScript file, for example app.ts, and import the necessary modules:
index.ts
import express, { Request, Response } from 'express';
54 chars
2 lines
  1. Create an instance of the Express application:
index.ts
const app = express();
23 chars
2 lines
  1. Define your API endpoints, for example:
index.ts
app.get('/api/v1/users', (req: Request, res: Response) => {
  res.send('List of users');
});

app.post('/api/v1/users', (req: Request, res: Response) => {
  res.send('Create user');
});

app.put('/api/v1/users/:id', (req: Request, res: Response) => {
  res.send(`Update user with ID ${req.params.id}`);
});

app.delete('/api/v1/users/:id', (req: Request, res: Response) => {
  res.send(`Delete user with ID ${req.params.id}`);
});
431 chars
16 lines
  1. Compile the TypeScript file to JavaScript by running tsc app.ts in your terminal.
  2. Run the server by running node app.js or nodemon app.js if you have installed nodemon.

Your API endpoints should now be available at http://localhost:3000/api/v1/users (or whichever port you have specified). You can test your API using a tool such as Postman.

gistlibby LogSnag