PostgreSQL REST API Connection: 2 Easy Methods

• October 19th, 2021

postgresql rest api: featured image

PostgreSQL is a powerful, open-source object-relational database system. It has more than 15 years of the 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 to create Restful applications with PostgreSQL as a database.

A REST API (also known as RESTful API) is an application programming interface (API or web API) . The API follows the constraints of REST architectural style and allows for interaction with RESTful web services. REST stands for representational state transfer.

This article gives 2 methods for PostgreSQL REST API connection.

Table of Contents

Introduction to REST API

PostgreSQL REST API: Rest API
Image Source: www.rlogical.com

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. This 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.

This freedom and flexibility inherent in REST API design allow you to build an API that meets your needs while also meeting the needs of very diverse customers. However, there are drawbacks to REST API design. You can lose the ability to maintain state in REST, such as within sessions, and it can be more difficult for newer developers to use. PostgreSQL REST API connection allows for a better interface to connect application to database.

REST API Design

PostgreSQL REST API: Rest API design
Image Source: miro.medium.com

Client-Server

The client-server constraint works on the concept that the client and the server should be separate from each other and allowed to evolve individually and independently.

Stateless

REST APIs are stateless, meaning that calls can be made independently of one another, and each call contains all of the data necessary to complete itself successfully. A REST API should not rely on data being stored on the server or sessions to determine what to do with a call, but rather solely rely on the data that is provided in that call itself.

Cache

A stateless API can increase request overhead by handling large loads of incoming and outbound calls, a REST API should be designed to encourage the storage of cacheable data.

Uniform Interface

The key to the decoupling client from the server is having a uniform interface that allows independent evolution of the application without having the application’s services, models, or actions tightly coupled to the API layer itself. The uniform interface lets the client talk to the server in a single language, independent of the architectural backend of either.

Layered System

As the name implies, a layered system is a system comprised of layers, with each layer having a specific functionality and responsibility. A layered system lets you encapsulate legacy systems and move less commonly accessed functionality to a shared intermediary while also shielding more modern and commonly used components from them.

Code on Demand

Code on Demand allows for code or applets to be transmitted via the API for use within the application. In essence, it creates a smart application that is no longer solely dependent on its own code structure.

Together, these constraints make up the theory of Representational State Transfer, or REST. These constraints make up a design that operates similarly to how we access pages in our browsers on the World Wide Web. It creates an API that is not dictated by its architecture, but by the representations.

Download the Ultimate Guide on Database Replication
Download the Ultimate Guide on Database Replication
Download the Ultimate Guide on Database Replication
Learn the 3 ways to replicate databases & which one you should prefer.

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

Hevo Data, a No-code Data Pipeline helps to load data from any data source such as Google Search Console, Databases, SaaS applications, Cloud Storage, SDKs, and Streaming Services and simplifies the ETL process. It supports 100+ data sources (including 30+ free data sources) and is a 3-step process by just selecting the data source, providing valid credentials, and choosing the destination. Hevo not only loads the data onto the desired Data Warehouse/destination but also enriches the data and transforms it into an analysis-ready form without having to write a single line of code.

GET STARTED WITH HEVO FOR FREE[/hevoButton]

Its completely automated pipeline offers data to be delivered in real-time without any loss from source to destination. Its fault-tolerant and scalable architecture ensure that the data is handled in a secure, consistent manner with zero data loss and supports different forms of data. The solutions provided are consistent and work with different BI tools as well.

Check out why Hevo is the Best:

  • Secure: Hevo has a fault-tolerant architecture that ensures that the data is handled in a secure, consistent manner with zero data loss.
  • Schema Management: Hevo takes away the tedious task of schema management & automatically detects the schema of incoming data and maps it to the destination schema.
  • Minimal Learning: Hevo, with its simple and interactive UI, is extremely simple for new customers to work on and perform operations.
  • Hevo Is Built To Scale: As the number of sources and the volume of your data grows, Hevo scales horizontally, handling millions of records per minute with very little latency.
  • Incremental Data Load: Hevo allows the transfer of data that has been modified in real-time. This ensures efficient utilization of bandwidth on both ends.
  • Live Support: The Hevo team is available round the clock to extend exceptional support to its customers through chat, email, and support calls.
  • Live Monitoring: Hevo allows you to monitor the data flow and check where your data is at a particular point in time.
SIGN UP HERE FOR A 14-DAY FREE TRIAL

Introduction to PostgreSQL

PostgreSQL REST API: PostgreSQL
Image Source: images.g2crowd.com

PostgreSQL is an open-source relational database management system (DBMS) developed by a worldwide team of volunteers. PostgreSQL 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. PostgreSQL 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. PostgreSQL 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 database.

Common Use cases of PostgreSQL

The following are the common use cases of PostgreSQL.

A robust database in the LAPP stack

LAPP stands for Linux, Apache, PostgreSQL, and PHP (or Python and Perl). PostgreSQL is primarily used as a robust back-end database that powers many dynamic websites and web applications.

General purpose transaction database

Large corporations and startups alike use PostgreSQL as primary databases to support their applications and products.

Geospatial database

PostgreSQL with the PostGIS extension supports geospatial databases for geographic information systems (GIS).

Key Features of PostgreSQL

PostgreSQL runs on all major operating systems, including Linux, UNIX (AIX, BSD, HP-UX, SGI IRIX, Mac OS X, Solaris, Tru64), and Windows. It supports text, images, sounds, and video, and includes programming interfaces for C / C++, Java, Perl, Python, Ruby, Tcl, and Open Database Connectivity (ODBC).

PostgreSQL supports a large part of the SQL standard and offers many modern features including the following −

  • Complex SQL queries
  • SQL Sub-selects
  • Foreign keys
  • Trigger
  • Views
  • Transactions
  • Multiversion concurrency control (MVCC)
  • Streaming Replication (as of 9.0)
  • Hot Standby (as of 9.0)

Procedural Languages Support

PostgreSQL supports four standard procedural languages, which allows the users to write their own code in any of the languages and it can be executed by PostgreSQL database server. These procedural languages are – PL/pgSQL, PL/Tcl, PL/Perl, and PL/Python. Besides, other non-standard procedural languages like PL/PHP, PL/V8, PL/Ruby, PL/Java, etc., are also supported.

Learn more about PostgreSQL.

Introduction to CRUD API

PostgreSQL REST API: CRUD API
Image Source:fiverr-res.cloudinary.com

When building an API, you want your model to provide four basic functionalities: it should be able to create, read, update, and delete resources. This set of essential operations is commonly referred to as CRUD.

RESTful APIs most commonly utilize HTTP requests. Four of the most common HTTP methods in a REST environment are GET, POST, PUT, and DELETE, which are the methods by which a developer can create a CRUD system.

Here’s how to apply CRUD in a REST environment:

  • Create — To create a resource in a REST environment, use the HTTP POST method
  • Read — To read a resource, use the GET method. Reading a resource retrieves data without altering it
  • Update — To update a resource, use the PUT method
  • Delete — To remove a resource from the system, use the DELETE method

PostgreSQL REST API Connection

PostgreSQL REST API: restful api
Image Source: postgrest.org

PostgreSQL REST API connection allows for better web and application platforms that can utilize PostgreSQL as a destination. REST API allows to generate a interface for seamless usage of PostgreSQL with the application.

Method 1: Using Javascript for CRUD operations

We’re going to create six functions for six routes that would perform PostgreSQL REST API connection.

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 2: using RAPID RESTful API for PostgreSQL REST API

Requirements:

  • 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:

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.

Conclusion

This article gave a comprehensive guide about REST API, PostgreSQL. It also gave two methods that can be used PostgreSQL REST API connection.

To make things easier, Hevo comes into the picture. Hevo Data is a No-code Data Pipeline and has awesome 100+ pre-built Integrations that you can choose from.

visit our website to explore hevo[/hevoButton]

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!

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

No-code Data Pipeline For your Data Warehouse