Using the PostGraphile NodeJs GraphQL API for Postgres

Introduction to the PostGraphile and NodeJs GraphQL API for Postgres

The schema that is precise makes all the difference in the time it takes to create PostgreSQL applications. Matter of fact, it’s possible that the PostGraphile GraphQL API can save developers up to several months in application development. Especially when using the JavaScript runtime environment, NodeJs. It is speedy and brings the power behind fast results for PostgreSQL complex queries. Learn with this tutorial that shows you how to use PostGraphile NodeJs GraphQL API Postgres. Then, you can query your PostgreSQL data tables in a most efficient way.

If you’re already familiar with how to use GraphQL API for Postgres, skip to Just the Code.

Prerequisites to using GraphQL with Postgres and NodeJs

  • Install PostgresSQL and run it. Port 5432 is the default.

  • Create a sample database and table with a few records in it to test the examples in this tutorial.

  • At a terminal window or command prompt, verify the installation with the postgres -V command.

  • Install NodeJs and NPM (Node Package Manager version 8.6 or later.

  • At a command prompt or in a terminal window, check your version of node with the command node -v.

Install the PostGraphile GraphQL API

NOTE: Here’s the PostGraphile API link.

  • First, try this method to do a global installation of the Node module postgraphile.
npm install -g postgraphile

Run PostGraphile in a Docker container

  • Use this command to use a Docker container to run PostGraphile:
docker pull graphile/postgraphile
docker run --init graphile/postgraphile --help

Run the PostGraphile API in a terminal window

  • Use the package runner NPX tool to run PostGraphile with the following command:
npx postgraphile --help
  • Use the following command to run the PostGraphile API. The options for watch, enhance, and dynamic are included in the code example.
npx postgraphile -c postgres://objectrocket:1234@localhost:5432/some_database --watch --enhance-graphiql --dynamic-json

NOTE: Make the Postgres settings the same as the parameters of the host, password, and username.

Screenshot of postgraphile API running in terminal on port 500

Test GraphQL API queries in your browser

  • Make sure the PostGraphile NodeJs Graphql API Postgres is running, and then in a browser tab, input the URL path of localhost, port 5000, and GraphQL GUI route.

  • After the app is finished fully loading, go to the tab in Explorer. See the dropdown arrow. Click it to pick the names that correspond with the table columns or the nodes for your request for your API.

  • Every Postgres record in a table is returned in the results with this code:

query MyQuery1 {
allSomeTableName {
edges {
node {
# column names go here
id
bool_col
int_col
str_col
}
}
}
}
  • Start the query by clicking the Play button or CTRL + ENTER.

Screenshot of the GraphQL GUI query app for PostgreSQL running as Node app

Running the PostGraphile GraphQL using a NodeJs script

You can create a basic GraphiQL app with the web framework for NodeJs called Express.

Declare the constants for the PostGraphile Node app

  • Make a code declaration for the modules in the app.
const http = require("http");
const express = require("express");
const { postgraphile } = require("postgraphile");

// Declare a constant for the Express app instance
const app = express();

Postgres parameters for the PostGraphile app

Here are the constants for you to link the parameters for concatenation for the URL string for your PostGraphile NodeJs GraphQL API Postgres app:

const user = "objectrocket";
const pass = "1234";
const port = "5432";
const dbName = "some_database";
const host = "localhost";

Concatenate a request URI for the PostGraphile app

  • Make a URL string concatenation for the API request out of Postgres parameters like this:
const dbUrl = `postgres://${user}:${pass}@${host}:${port}/${dbName}`;
console.log("\nPostgres origin URL for connection:\n", dbUrl);

Use the Express module’s app instance to create a web server

  • Create an API server for PostGraphile with an instance of the Express module. To do this, pass the URL string with the method postgraphile(). Start the process with the method use() as shown in the code here:
app.use(
  postgraphile(dbUrl, "public", {
    ignoreRBAC: true, // Role Based Access Control (RBAC)
    extendedErrors: ["errcode", "detail", "hint"],
    graphiql: true
  })
);

// Use Express to listen on a port
var server = app.listen(process.env.PORT || 2000, function() {
  console.log("postgraphile API running on port:", server.address().port);
});
  • Execute it. To do this, save the code, and then use the command node and type the name of the code you just saved:
node postgraphile-test.js
  • In a browser window, display the GraphiQL Node app. Go to http://localhost:2000/graphiql.

Screenshot of the Express Node app for the PostGraphile GraphiQL API running in a browser tab

NOTE: When finished with your API requests and alterations, end PostGraphile; otherwise, the processes will keep running. You can press CTRL + C to cancel and make the application inactive.

Conclusion to the PostGraphile NodeJs GraphQL API Postgres tutorial

This concludes this tutorial where you learned how to create PostGraphile NodeJs GraphQL API Postgres. You learned how to create a PostGraphile app, create the API server, and test queries using the runtime environment of NodeJs. Try these steps out on a regular basis to expedite your queries and response times for your Postgres data.

Just the Code

Here’s the code for the examples given in this tutorial about PostGraphile NodeJs Graphql API Postgres.

const http = require("http");
const express = require("express");
const { postgraphile } = require("postgraphile");

// Declare a constant for the Express app instance
const app = express();

// PostgreSQL parameters to pass to the URL origin
const user = "objectrocket";
const pass = "1234";
const port = "5432";
const dbName = "some_database";
const host = "localhost";

// Concatenate the origin URL from the PostgreSQL parameters
const dbUrl = `postgres://${user}:${pass}@${host}:${port}/${dbName}`;
console.log("\nPostgres origin URL for connection:\n", dbUrl);

// Call the Express app's 'use()' method
app.use(
  postgraphile(dbUrl, "public", {
    ignoreRBAC: true, // Role Based Access Control (RBAC)
    extendedErrors: ["errcode", "detail", "hint"],
    graphiql: true
  })
);

// Use Express to listen on a port
var server = app.listen(process.env.PORT || 2000, function() {
  console.log("postgraphile API running on port:", server.address().port);
});

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.