step-by-step guide on how to set up a simple REST API using Node.js, PostgreSQL, Express, TypeScript, and Docker.

By | 6 months ago

psqlrest api docker node js express js starter

Here's a step-by-step guide on how to set up a simple REST API using Node.js, PostgreSQL, Express, TypeScript, and Docker. This guide will include a `GET` endpoint to retrieve data and a `POST` endpoint to insert data into the database.

Step 1: Initialize the Project

Create a new directory for your project and navigate into it:

mkdir my-api-postgres cd my-api-postgres

Initialize a new Node.js project:

npm init -y

Step 2: Install Dependencies

Install the necessary packages:

npm install express pg body-parser npm install typescript ts-node @types/node @types/express @types/pg @types/body-parser --save-dev

Step 3: Set up TypeScript

Initialize TypeScript in your project:

npx tsc --init

Modify the `tsconfig.json` to include the following settings:

{ "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 { Pool } from 'pg'; const app = express(); const PORT = 3000; app.use(bodyParser.json()); const pool = new Pool({ host: 'localhost', user: 'postgres', password: 'password', database: 'mydatabase', port: 5432 }); app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); });

Step 5: Integrate PostgreSQL

Modify `server.ts` to include PostgreSQL integration using the `pg` library:

// GET API to fetch all items app.get('/items', async (req, res) => { const { rows } = await pool.query('SELECT * FROM items'); res.status(200).json(rows); }); // POST API to add a new item app.post('/items', async (req, res) => { const { name, quantity } = req.body; const { rows } = await pool.query('INSERT INTO items(name, quantity) VALUES($1, $2) RETURNING *', [name, quantity]); res.status(201).json(rows[0]); });

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: - db db: image: postgres environment: POSTGRES_DB: mydatabase POSTGRES_USER: postgres POSTGRES_PASSWORD: password ports: - "5432:5432"

Step 7: Run Your Application

Build and run your Docker containers:

docker-compose up --build

This setup gives you a REST API running in a Docker container, connected to a PostgreSQL database also in a Docker container. You have a `GET` endpoint at `/items` to fetch all items and a `POST` endpoint at `/items` to add new items. Adjust your database credentials and queries as needed to match your environment.