PostgreSQL is a powerful, open-source object-relational database system. It has more than 15 years of active development phase and a proven architecture that has earned it a strong reputation for reliability, data integrity, and correctness. PostgreSQL REST API connection allows you to create Restful applications with PostgreSQL as a database. The Postgres REST API provides a convenient way to interact with your database through HTTP requests.

Now, without any further delay, let’s read this article and learn about the three methods for REST API PostgreSQL integration and PostgreSQL REST API example.

What is PostgreSQL?

PostgreSQL is an open-source relational database management system (RDBMS) developed by a worldwide team of volunteers. It is not controlled by any corporation or other private entity and the source code is available free of charge. PostgreSQL is an advanced, enterprise-class, and open-source relational database system, and supports both SQL (relational) and JSON (non-relational) querying.

PostgreSQL is a highly stable database backed by more than 20 years of development by the open-source community. It is used as a primary database for many web applications as well as mobile and analytics applications. PostgreSQL REST API connection allows for better utilization of the database.

What is REST API?

REST API is also known as RESTful API. REST is an acronym for Representational State Transfer. REST is designed in such a way that it can be used over nearly any protocol. It usually takes advantage of HTTP when used for Web APIs. It must be noted that there are critical differences between REST API and Web APIs, and they cannot be used interchangeably.

The architecture of REST allows developers to utilize the resources without needing to install libraries or additional software in order to take advantage of a REST API design. It is notable for its incredible layer of flexibility. Since data is not tied to methods and resources, REST has the ability to handle multiple types of calls, return different data formats and even change structurally with the correct implementation of hypermedia.

Methods for PostgreSQL Rest API Connection

Simplify Data Analysis with Hevo’s No-code Data Pipeline

Hevo is the only real-time ELT No-code Data Pipeline platform that cost-effectively automates data pipelines that are flexible to your needs. With integration with 150+ Data Sources (40+ free sources), we help you not only export data from sources & load data to the destinations but also transform & enrich your data, & make it analysis-ready.

Start for free now!

Get Started with Hevo for Free

PostgreSQL REST API Connection

PostgreSQL REST API: restful api

Image Source

PostgreSQL REST API connection allows for better web and application platforms that can utilize PostgreSQL as a destination. REST API allows the generation of an interface for seamless usage of PostgreSQL with the application. The Postgres API offers a wide range of functions for managing and querying relational databases.

Click here to learn more about the differences between API and Rest API 

And now that you’re familiar with the concept, let’s read about three simple methods to create an API to get data from PostgreSQL.

Click here to learn more about how to use command lines in PostgreSQL.

Method 1: Using Hevo Data for PostgreSQL REST API Connection

Hevo Data, a No-code Data Pipeline, helps you transfer data for REST API PostgreSQL Connection.

Hevo Data focuses on two simple steps to get you started with REST API to PostgreSQL Integration:

  • Configure Source: Connect Hevo Data with your REST API source by providing a unique name for your pipeline and information about the method you want to use, choosing between GET and POST. You will also need to provide the URL for your API endpoint, the data root for your API, and your credentials such as username and password to allow Hevo to access your data, along with information about your query params and API headers.
PostgreSQL REST API: Configure REST API as a Source
  • Configure Destination: Select PostgreSQL as your destination and fill in the credentials as shown below to set up connect REST API to PostgreSQL.
PostgreSQL REST API: Configure PostgreSQL as a Destination

Method 2: Using Javascript for CRUD operations

We’re going to create six functions for six routes that would create REST API for Postgres.

First, create all the functions for each route. Then, export the functions so they’re accessible:

  • GET — / | displayHome()
  • GET — /users | getUsers()
  • GET — /users/:id | getUserById()
  • POST — users | createUser()
  • PUT — /users/:id | updateUser()
  • DELETE — /users/:id | deleteUser()

In index.js, we made an app.get() for the root endpoint with a function in it. Now in queries.js, we’ll create endpoints that will display all users, display a single user, create a new user, update an existing user, and delete a user.

GET all users

Our first endpoint for PostgreSQL REST API will be a GET request. Inside the pool.query() we can put the raw SQL that will touch the PostgreSQL REST API database. We’ll SELECT all users and order by id.

const getUsers = (request, response) => {
  pool.query('SELECT * FROM users ORDER BY id ASC', (error, results) => {
    if (error) {
      throw error
    }
    response.status(200).json(results.rows)
  })
}

GET a single user by ID

For our /users/:id request, we’ll be getting the custom id parameter by the URL and using a WHERE clause to display the result.

const getUserById = (request, response) => {
  const id = parseInt(request.params.id)

  pool.query('SELECT * FROM users WHERE id = $1', [id], (error, results) => {
    if (error) {
      throw error
    }
    response.status(200).json(results.rows)
  })
}

POST a new user

The PostgreSQL REST API will take a GET and POST request to the /users endpoint. In the POST request, we’ll be adding a new user. In this function, we’re extracting the name and email properties from the request body, and INSERTing the values.

const createUser = (request, response) => {
  const { name, email } = request.body

  pool.query('INSERT INTO users (name, email) VALUES ($1, $2)', [name, email], (error, results) => {
    if (error) {
      throw error
    }
    response.status(201).send(`User added with ID: ${result.insertId}`)
  })
}

PUT updated data in an existing user

The /users/:id endpoint will also take two HTTP requests — the GET we created for getUserById, and also a PUT, to modify an existing user. For this query, we’ll combine what we learned in GET and POST to use the UPDATE clause.

It is worth noting that PUT is idempotent, meaning the exact same call can be made over and over and will produce the same result. This is different than POST, in which the exact same call repeated will continuously make new users with the same data.

const updateUser = (request, response) => {
  const id = parseInt(request.params.id)
  const { name, email } = request.body

  pool.query(
    'UPDATE users SET name = $1, email = $2 WHERE id = $3',
    [name, email, id],
    (error, results) => {
      if (error) {
        throw error
      }
      response.status(200).send(`User modified with ID: ${id}`)
    }
  )
}

DELETE a user

Finally, we’ll use the DELETE clause on /users/:id to delete a specific user by id. This call is very similar to our getUserById() function.

const deleteUser = (request, response) => {
  const id = parseInt(request.params.id)

  pool.query('DELETE FROM users WHERE id = $1', [id], (error, results) => {
    if (error) {
      throw error
    }
    response.status(200).send(`User deleted with ID: ${id}`)
  })
}

Exporting CRUD functions in a PostgreSQL REST API

To access these functions from index.js, we’ll need to export them. We can do this with module.exports, creating an object of functions. Since we’re using ES6 syntax, we can write getUsers instead of getUsers:getUsers, and so on.

module.exports = {
  getUsers,
  getUserById,
  createUser,
  updateUser,
  deleteUser,
}

Here is our complete queries.js file.

const Pool = require('pg').Pool
const pool = new Pool({
  user: 'me',
  host: 'localhost',
  database: 'api',
  password: 'password',
  port: 5432,
})
const getUsers = (request, response) => {
  pool.query('SELECT * FROM users ORDER BY id ASC', (error, results) => {
    if (error) {
      throw error
    }
    response.status(200).json(results.rows)
  })
}

const getUserById = (request, response) => {
  const id = parseInt(request.params.id)

  pool.query('SELECT * FROM users WHERE id = $1', [id], (error, results) => {
    if (error) {
      throw error
    }
    response.status(200).json(results.rows)
  })
}

const createUser = (request, response) => {
  const { name, email } = request.body

  pool.query('INSERT INTO users (name, email) VALUES ($1, $2)', [name, email], (error, results) => {
    if (error) {
      throw error
    }
    response.status(201).send(`User added with ID: ${result.insertId}`)
  })
}

const updateUser = (request, response) => {
  const id = parseInt(request.params.id)
  const { name, email } = request.body

  pool.query(
    'UPDATE users SET name = $1, email = $2 WHERE id = $3',
    [name, email, id],
    (error, results) => {
      if (error) {
        throw error
      }
      response.status(200).send(`User modified with ID: ${id}`)
    }
  )
}

const deleteUser = (request, response) => {
  const id = parseInt(request.params.id)

  pool.query('DELETE FROM users WHERE id = $1', [id], (error, results) => {
    if (error) {
      throw error
    }
    response.status(200).send(`User deleted with ID: ${id}`)
  })
}

module.exports = {
  getUsers,
  getUserById,
  createUser,
  updateUser,
  deleteUser,
}

Setting up CRUD functions in a REST API

Now that we have all of our queries, the last thing we need to do is pull them into the index.js file and make endpoint routes for all the query functions we created.

To get all the exported functions from queries.js, we’ll require the file and assign it to a variable.

const db = require('./queries')

Now for each endpoint, we’ll set the HTTP request method, the endpoint URL path, and the relevant function.

app.get('/users', db.getUsers)
app.get('/users/:id', db.getUserById)
app.post('/users', db.createUser)
app.put('/users/:id', db.updateUser)
app.delete('/users/:id', db.deleteUser)
Here is our complete index.js, the entry point of the API server.
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const db = require('./queries')
const port = 3000

app.use(bodyParser.json())
app.use(
  bodyParser.urlencoded({
    extended: true,
  })
)

app.get('/', (request, response) => {
  response.json({ info: 'Node.js, Express, and Postgres API' })
})

app.get('/users', db.getUsers)
app.get('/users/:id', db.getUserById)
app.post('/users', db.createUser)
app.put('/users/:id', db.updateUser)
app.delete('/users/:id', db.deleteUser)

app.listen(port, () => {
  console.log(`App running on port ${port}.`)
})

Method 3: Using RAPID RESTful API for PostgreSQL REST API

  • OS: Linux, Windows
  • NodeJS
  • OpenSSL should be installed before in order to allow the server to create it’s first self-signed SSL certificate.
  • Tested with Posgresql 9.3 and up
  • Linux – set your computer to accept opening lower ports without root access for NodeJs (80/443), next code works for Ubuntu 14.
sudo apt-get install libcap2-bin sudo setcap cap_net_bind_service=+ep /usr/local/bin/node

INSTALLATION ( install local is required –save)

npm install psql-api --save

sample new server.js code:

server = require("psql-api");
server.start();

Install from git as standalone server:

git clone https://github.com/QBisConsult/psql-api.git

Run this inside the new server folder:

sudo npm install

Run the server with:

node start.js

This server will open two ports, one for administration on HTTPS (443) and another for PostgreSQL REST API requests.

The server can be managed at:

https://server_Ip_or_domain name

It will use a self-signed SSL certificate generated at the first start until you will provide an authorized one or change with your own.

If OpenSSL can not be found, you will need to provide an SSL certificate otherwise the server will not start. Put the certificate into the “SSL” folder as service.crt and service.key files. The SSL certificate is a PEM encoded crt file.

You can change the server port and protocol (HTTP/HTTPS) for PostgreSQL REST API access from settings page.

PostgreSQL REST API implements all CRUD operations (CREATE, READ, UPDATE, DELETE). PostgreSQL REST API automatically imports the database structure and creates metadata of your database. Single point access, accept POST/PUT/GET/DELETE HTTP methods and respond with a JSON data object.

Basic operations can be used from the start:

CREATE - insert records
READ - read one record by ID
UPDATE - update one record
DELETE - delete one record

The servers accept a batch of different commands at once and use transactions by default.

Inject your code BEFORE and AFTER operations in order to customize access to each action.

Management of the database structure requires a third-party application like pgAdmin or others. This PostgreSQL REST API server will check requests before sending them to the database against metadata created at the start in order to avoid unnecessary traffic with the database server, the server will need to update its metadata if database changes occur. This PostgreSQL REST API server will not alter the database structures and it is no plan to do that in the future.

PostgreSQL REST API server can be used to offer WEB services for various kind of applications and devices over HTTP/HTTPS protocol like WEB, mobile or IoT applications that consumes WEB services.

Curious to know the difference between RESTFUL APIs and REST APIs? Read this blog for more information.

Method 4 : Automatic APIs With PostgREST for PostgreSQL

To demonstrate how to get started with PostgREST, you will want to establish an API schema using the Psql Tool.

CREATE SCHEMA api; 

Then, within that schema, construct a table containing data that the API can serve up. In this example, you will design a basic table for a list of books with the following columns and data types:

CREATE TABLE api.books (
    index SERIAL,
    title TEXT,
    author VARCHAR(255),
    genre TEXT,
);

Note : The index column has the SERIAL type, which means it will generate an auto-incremented ID for each entry produced in the table. To begin, insert a few rows, each including a book title, author, and genre.

PostgREST Security

Using PostgreSQL roles as the RESTful API users, PostgREST assigns security to the database. You’ll want to establish a position with few privileges. In this case, the position is named apiOperator. It will be unable to connect in to the server and will only have access to the books table via API:

CREATE ROLE apiOperator nologin;
GRANT usage ON SCHEMA api TO apiOperator;
GRANT all ON api.books TO apiOperator;
GRANT usage, SELECT ON SEQUENCE api.books_index_seq TO operator;

This completes the basic Postgres configuration, and you can now proceed to configure PostgREST to communicate with your database server.

PostgREST Configuration

PostgREST relies on postgrest.conf, a small configuration file with only a few variables. You’ll need to supply the URI for your Postgres server, as well as the schema containing the data to be accessed via API calls and the role to which you’ll connect.

In this example, we’ll assume you’re running PostgREST on the same server as your PostgreSQL database (localhost). As previously said, our sample schema is api, and the role’s name is apiOperator. Put these arguments in the configuration file like this:

db-uri = "localhost"
db-schema = "api"
db-anon-role = "apiOperator"

Once you’ve saved the configuration file, you’re ready to perform your first API request using PostgREST.

Making an API Call Using PostgREST

Assuming you’re running PostgREST on localhost with your database server, as described previously, the following HTTP request will return all rows from your books table.

curl "http://localhost:3000/books"

PostgREST provides a variety of filters to limit the results returned. For example, to obtain the first five rows from the books table, perform this Curl request:

curl "http://localhost:3000/books?limit=5"

You may also specify specific columns from the table you want returned. This request will return only the book title and author of the first five rows:

curl "http://localhost:3000/books?limit=5&select=title,author"

As previously stated, PostgREST supports complete CRUD functionalities. The examples above demonstrate the R (“read”) function in operation. Here’s how to set a new record:

curl "http://localhost:3000/books" \
    -X POST -H "Content-Type: application/json" \
    -d \
    '
    {
        "author": "Ernest Hemingway",
        "title": "The Sun Also Rises"
    }
    '

And here’s how you can remove the record that was just added:

curl -X DELETE "http://localhost:3000/books?title=like."The Sun*"

PostgREST: Features Overview

PostgREST is equipped with the following functionalities by default:

  • A single point of truth with a standardized API.
  • API creation from scratch, with no custom code.
  • Access all CRUD operations in a secure way.

PostgresREST builds APIs well, however it lacks features for more advanced applications. Many users still desire the ability to modify the API, send emails, and develop additional unique business logic. 

To achieve these goals, PostgreSQL’s capability must be paired with custom programming and some of the open-source PostgREST apps and extensions.

Pros and Cons of PostgREST

PostgREST is just a web server that can convert your PostgreSQL database into a REST API. This eliminates the need to manually define your CRUD endpoints, but it doesn’t provide anything more without significant additional effort. Below are the advantages and disadvantages of PostgREST.

PostgREST Pros

  • Provides lightweight middleware.
  • Simple SQL queries will help you construct your API.
  • Integrates with OpenAPI to create interactive documentation.

PostgREST Cons

  • No native graphical user interface (GUI).
  • API documentation is not automatically created.
  • To construct each endpoint, you must have SQL understanding.
  • Allows non-secure APIs to be released while limiting row-level security.

Keeping all of these in mind, PostgREST will have limited utility in the company. Unless your whole digital strategy revolves on a Postgres data warehouse, and you have the developer resources to expand PostgREST’s limited capability, you will want a more complete API management solution.

Because most firms handle a variety of apps and services, an API management platform is more likely to meet your entire requirements.

Conclusion

This article gave a comprehensive guide about REST API and PostgreSQL. It also gave four methods that can be used for REST API PostgreSQL migration.

Hevo can help you integrate your data from numerous sources and load them into a destination to analyze real-time data with a BI tool such as Tableau. It will make your life easier and data migration hassle-free. It is user-friendly, reliable, and secure.

SIGN UP for a 14-day free trial and see the difference! Check out our pricing to choose the best plan for you.

Share your experience learning about PostgreSQL REST API in the comments section below.

Arsalan Mohammed
Research Analyst, Hevo Data

Arsalan is a research analyst at Hevo and a data science enthusiast with over two years of experience in the field. He completed his B.tech in computer science with a specialization in Artificial Intelligence and finds joy in sharing the knowledge acquired with data practitioners. His interest in data analysis and architecture drives him to write nearly a hundred articles on various topics related to the data industry.

No-code Data Pipeline For your Data Warehouse