Node.js GraphQL & PostgreSQL Quickstart

2 minute read

View the source code here

GraphQL is an API query language that aims to replace REST. With GraphQL, you can combine data from multiple sources into one response and expose it as a single API endpoint. We’ll explore one option in this below: querying data from PostgreSQL.

Prerequisites

From your terminal, install the necessary packages:

npm i pg-promise graphql graphql-tools cors body-parser express graphql-server-express

PostgreSQL Connection

First, we’ll setup a PostgreSQL connection instance:

Sample GraphQL Resolver

Now, let’s create a simple GraphQL resolver to retrieve the data from Postgres:

Sample GraphQL Schema

Next, we’ll tell GraphQL which fields we can query and what values to expect in the response:

Sample GraphQL Server

Last, spin up an express server hosting our new API:

Conclusion

And that’s it! You can now point your browser to localhost:3000/graphiql for a GUI representation. Don’t forget to create your users table in Postgres!


If you enjoyed this article, please help out with a like, a share, or a comment. It fuels my focus to write more of it, thanks!

James Mensch is the Director of Engineering at Threatcare and the CEO at Magnifai. I believe in building intelligent products, using data to drive decisions, and engineering for social impact. I write about some of the cool stuff I do with tech, productivity and motivation psychology, and my social innovation projects. Connect with me on LinkedIn or say hi on Twitter.