Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources
Accessing PostgreSQL Data via REST API

Accessing PostgreSQL Data via REST API

REST API (Representational State Transfer) is a popular way to expose data from a database to a web application. This tutorial will guide you through the process of creating a REST API to access PostgreSQL data.

1. Prerequisites

Before you begin, make sure you have the following:

  • PostgreSQL installed and running on your machine or server.
  • Basic understanding of PostgreSQL and SQL queries.
  • Basic knowledge of web development and REST APIs.
  • A web server or application server to host the REST API (e.g., Node.js, Python Flask, or Java Spring Boot).

2. Setting Up the Environment

We will use Node.js with the Express framework to create our REST API. Follow these steps to set up the environment:

  1. Install Node.js from the official website: https://nodejs.org/
  2. Create a new directory for your project and navigate to it in your terminal:
  3. mkdir pg-rest-api
    cd pg-rest-api
  4. Initialize a new Node.js project:
  5. npm init -y
  6. Install the required dependencies:
  7. npm install express pg body-parser

3. Creating the REST API

Follow these steps to create the REST API:

  1. Create a new file named server.js in your project directory.
  2. Open server.js and add the following code to set up the Express server and connect to PostgreSQL:
  3. const express = require('express');
    const bodyParser = require('body-parser');
    const { Pool } = require('pg');
    
    const app = express();
    const port = 3000;
    
    // Middleware
    app.use(bodyParser.json());
    
    // PostgreSQL connection pool
    const pool = new Pool({
      user: 'your_username',
      host: 'localhost',
      database: 'your_database',
      password: 'your_password',
      port: 5432,
    });
    
    // Test endpoint
    app.get('/', (req, res) => {
      res.send('Hello World!');
    });
    
    // Start the server
    app.listen(port, () => {
      console.log(`Server running on port ${port}`);
    });
                    

4. Creating API Endpoints

Next, we will create API endpoints to perform CRUD (Create, Read, Update, Delete) operations on our PostgreSQL database.

4.1. Create (POST)

Add the following code to server.js to create a new record in the database:

app.post('/users', async (req, res) => {
  const { name, email } = req.body;
  try {
    const result = await pool.query(
      'INSERT INTO users (name, email) VALUES ($1, $2) RETURNING *',
      [name, email]
    );
    res.status(201).json(result.rows[0]);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});
            

4.2. Read (GET)

Add the following code to server.js to read records from the database:

app.get('/users', async (req, res) => {
  try {
    const result = await pool.query('SELECT * FROM users');
    res.status(200).json(result.rows);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});
            

4.3. Update (PUT)

Add the following code to server.js to update a record in the database:

app.put('/users/:id', async (req, res) => {
  const { id } = req.params;
  const { name, email } = req.body;
  try {
    const result = await pool.query(
      'UPDATE users SET name = $1, email = $2 WHERE id = $3 RETURNING *',
      [name, email, id]
    );
    res.status(200).json(result.rows[0]);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});
            

4.4. Delete (DELETE)

Add the following code to server.js to delete a record from the database:

app.delete('/users/:id', async (req, res) => {
  const { id } = req.params;
  try {
    await pool.query('DELETE FROM users WHERE id = $1', [id]);
    res.status(204).send('User deleted');
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});
            

5. Testing the REST API

To test the REST API, you can use a tool like Postman or cURL. Here are some example requests:

5.1. Create a User

POST /users
Content-Type: application/json

{
  "name": "John Doe",
  "email": "john.doe@example.com"
}
            

5.2. Get All Users

GET /users
            

5.3. Update a User

PUT /users/1
Content-Type: application/json

{
  "name": "Jane Doe",
  "email": "jane.doe@example.com"
}
            

5.4. Delete a User

DELETE /users/1
            

6. Conclusion

In this tutorial, we covered the basics of creating a REST API to access PostgreSQL data. We set up a Node.js server with Express, connected to a PostgreSQL database, and created CRUD endpoints. You can extend this basic setup to fit your specific needs and integrate it with your web applications.