GraphQL API Integration for Full-Stack Apps with PostGraphile
Tags: graphql, api, backend, postgraphile
Published: 2022-10-24 14:20:01

In part two of this tutorial series, we’re going to look at the key features of GraphQL and how to integrate it with PostGraphile to enhance the back-end of our full-stack application.

In part one, we covered how to approach building a GraphQL API with TypeScript and Node.js as well as the key benefits of this architecture. If you missed it, check out how we set up the project and bootstrapped our code by installing dependencies and configuring our data model. 

## What is GraphQL?
In a nutshell, GraphQL acts as a layer to fetch and mutate data. It’s language-agnostic on both the front and back-end (e.g. JavaScript, Java, C#, Go, PHP, etc.) and serves as a bridge between client and server communications.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ai1l105xyv0qvb4vky54.png)

The goal of GraphQL is to provide methods for retrieving and modifying data. To provide this function, GraphQL has several operations: 

- **Queries**: for performing data fetching operations on the server.
- **Mutations**: analogue to the standard CRUD (Create, Retrieve, Update, Delete) operations, except for the Retrieve (for which Queries are responsible in GraphQL).
- **Subscriptions**: conceptually, subscriptions are like Queries in that it’s utilized to fetch data. It may maintain an active connection to your GraphQL server to enable the server to push live updates for the subscribed clients.
- **Resolvers**: Resolvers are implemented in the back-end as handlers for the lookup logic for the requested resources.

It’s important to mention that GraphQL isn’t a framework/library, nor a database implementation/query language for the DB. Rather, it’s a specification powered by a robust type system called Schema Definition Language (GraphQL SDL) described in its specs. It serves as a mechanism to enforce a well-defined schema that serves like a contract establishing what is and what isn’t allowed.

It’s a wrong assumption to think that GraphQL is a database implementation or a query language tied to any particular database. Although it’s common to see that being translated to DB interactions, it’s possible to use GraphQL even without having any sort of DB (ex., you can set up a GraphQL layer to expose and orchestrate different REST APIs endpoints).

## Using PostGraphile to Integrate with GraphQL
There are a few ways to set up a GraphQL API in Node.js. These options may include: 

- Apollo Server
- Hasura
- Prisma
- PostGraphile

Alternatively, you can build your own server with custom resolvers and a schema definition. While there are pros and cons for each method, we’ll use PostGraphile in this tutorial. We’ve made that choice because it provides an instant GraphQL API based on the DB schema.

## What Is PostGraphile?
PostGraphile is a powerful tool that makes it easy to set up a robust GraphQL API relatively quickly. According to the official documentation:

_“PostGraphile automatically detects tables, columns, indexes, relationships, views, types, functions, comments, and more — providing a GraphQL server that is highly intelligent about your data, and that automatically updates itself without restarting when you modify your database.”_

This makes PostGraphile a great option for developers because it enables them to build fast, reliable APIs. Some of the key features that make this possible are:

- Strong PostgreSQL support
- Use of GraphQL best practices
- Simplicity to deploy and scale
- Customizability 
- Impressively high performance
- Granular authorisation via RLS
- Open source under MIT license
- Powerful plugin system

## Configuring PostGraphile

There are two ways of integrating PostGraphile into our project: via **PostGraphile CLI** or through a middleware. For this project, we’ll use a middleware.

Now that we have an overview of GraphQL and how **PostGraphile** can be helpful in our demo project, let’s go ahead and install the **PostGraphile** dependency in our project.

```
npm install postgraphile@^4.12.9
```

To use PostGraphile in our application, we need to import it like our other dependencies. The import can be added to the top of the App.ts file:

```
import postgraphile from 'postgraphile'
```

After that, all we need to do to complete the setup is to enhance our App.ts and bootstrap our Express server with PostGraphile Middleware. To do that, replace this code section:

```
/**
* This is our main entry point of our Express server.
* All the routes in our API are going to be here.
**/
const App = () => {
 const app = express()
 app.use(express.json())
```

With this:

```
const pgUser = '*** INSERT YOUR POSTGRESQL USER HERE ***'

/**
* This is our main entry point of our Express server.
* All the routes in our API are going to be here.
**/
const App = () => {
 const app = express()
 app.use(express.json())
 app.use(postgraphile(`postgresql://${pgUser}@localhost/catalog_db`, 'public', {
   watchPg: true,
   graphiql: true,
   enhanceGraphiql: true,
 }))
```

We’re basically configuring the **PostGraphile** middleware in our server.

Now, if you restart the server and hit the http://localhost:8090/graphiql in your browser, you’re going to see some really interesting stuff! We’ll dig into all of that in the next section. 

Note: if, when restarting the server, you see: 

- _“Failed to setup watch fixtures in Postgres database”_ 
- _“A serious error occurred when building the initial schema. Exiting because `retryOnInitFail` is not set”_

_Then make sure the user specified in the **const pgUser =** is valid and that you have the admin privileges for changing the Postgres DB Schema._

## GraphQL Playground
GraphQL Playground is a sort of IDE for exploring and interacting with a GraphQL server. It comes with an interactive UI that can run on the browser to where you can build and test queries/mutations and explore the GraphQL schemas.

What you are seeing is an enhanced version of GraphiQL shipped with PostGraphile. While it’s out of the scope of this tutorial to dive deep into the GraphQL playground, we’ll cover some of the key features that it provides.

## GraphQL API Documentation
Our GraphQL Playground can also serve as an API documentation with the powerful schema introspection feature. Let’s take a look.

First, in the top right-corner, click on the **“< Docs”** option. This will open the **Documentation Explorer**:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ftedzzmokg9m0ckjd65n.png)

There are two root types enabled: **Query** and **Mutation**. Let’s explore the **Query** type.

If you scroll down, you’ll see many options available to use. In TypeORM, we defined the entities to be added to the PostgreSQL server. The PostGraphile middleware is able to automatically expose these entities to GraphQL, allowing us to access them through GraphiQL.

Let’s take a look at the **allCategories** query as an example:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l65qckuzeiocyqvtfps4.png)

By clicking on the **allCategories** hyperlink, you can see the details of that query:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k6tx374iykj5tagytnm2.png)

This window displays the different methods you can use to work with the query results.

Notice that GraphQLsupports Cursor (after, before) and Offset (first/last, offset) based pagination, Ordering and Filters (condition), with all of that supported out of the box!

As for the **Mutation** type, you have access to create, update and delete utilities for all of our entities!

In the following sections, we’ll explore some of the fundamental features of a GraphQL API: writing Queries and Mutations.

_Note: this article is not going to cover all the details of writing **Queries** and **Mutations**. If you’re interested in this, there are some great resources on the official GraphQL Foundation website._

Want to learn more? I would highly recommend this article: [GraphQL API Integration for Full-Stack Apps with PostGraphile [Tutorial Part 2]](https://www.scalablepath.com/full-stack/graphql-and-postgraphile-integration-full-stack-tutorial-part-2)