step-by-step guide on how to create a simple REST API using Node.js, MongoDB, Express, TypeScript, and Docker
By | 6 months ago
Step 1: Initialize the project
Create a new directory for your project and navigate into it:
mkdir my-api cd my-api
Initialize a new Node.js project:
npm init -y
Step 2: Install dependencies
Install the necessary packages:
npm install express mongoose body-parser npm install typescript ts-node @types/node @types/express @types/mongoose @types/body-parser --save-dev
Step 3: Set up TypeScript
Initialize TypeScript in your project:
npx tsc --init
Edit the `tsconfig.json` to include the following:
{ "compilerOptions": { "target": "es6", "module": "commonjs", "outDir": "./dist", "rootDir": "./src", "strict": true, "esModuleInterop": true }, "include": ["src/**/*"] }
Step 4: Create your Express server
Create a `src` directory and a `server.ts` file:
mkdir src cd src touch server.ts
In server.ts
, set up a basic Express server:
import express from 'express'; import bodyParser from 'body-parser'; import mongoose from 'mongoose'; const app = express(); const PORT = 3000; app.use(bodyParser.json()); app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); });
Step 5: Integrate MongoDB with Mongoose
Modify `server.ts` to include Mongoose for MongoDB integration:
mongoose.connect('mongodb://mongo:27017/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true }).then(() => console.log('MongoDB connected')) .catch(err => console.log(err)); // Define a schema and model const Schema = mongoose.Schema; const itemSchema = new Schema({ name: String, quantity: Number }); const Item = mongoose.model('Item', itemSchema); // GET API to fetch all items app.get('/items', async (req, res) => { try { const items = await Item.find(); res.status(200).json(items); } catch (error) { res.status(500).json({ message: error.message }); } }); // POST API to add a new item app.post('/items', async (req, res) => { const newItem = new Item({ name: req.body.name, quantity: req.body.quantity }); try { const savedItem = await newItem.save(); res.status(201).json(savedItem); } catch (error) { res.status(400).json({ message: error.message }); } });
Step 6: Dockerize the application
Create a `Dockerfile` in the root directory:
FROM node:14 WORKDIR /usr/src/app COPY package*.json ./ RUN npm install COPY . . EXPOSE 3000 CMD ["npm", "start"]
Create a `docker-compose.yml` file:
version: '3.8' services: app: build: . ports: - "3000:3000" volumes: - .:/usr/src/app depends_on: - mongo mongo: image: mongo ports: - "27017:27017"
Step 7: Run your application
Build and run your Docker containers:
docker-compose up --build
This setup will give you a REST API running in a Docker container, connected to a MongoDB database, also running in a Docker container. Your API will have a `GET` endpoint at `/items` to fetch all items and a `POST` endpoint at `/items` to add new items.