Open In App

Building GraphQL APIs with PostgreSQL

Last Updated : 19 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

GraphQL and PostgreSQL are powerful technologies that play important roles in modern web development. GraphQL a query language for APIs, revolutionizes how clients interact with servers by allowing them to request specific data. On the other hand, PostgreSQL, an advanced relational database management system, offers reliability, performance and extensive features for storing and managing data. In this article, We will learn about GraphQL, PostgreSQL, also Creating a GraphQL API with PostgreSQL with the practical implementation in detail and so on.

What are GraphQL and PostgreSQL?

GraphQL:

  • GraphQL is a query language for APIs that allows clients to request specific data they need, rather than depend on the server to determine the structure of the response.
  • This enables clients to fetch only the required data, reducing the amount of data transferred over the network and improving performance.
  • GraphQL also provides a single endpoint for all API requests, simplifying client-server communication.

PostgreSQL:

  • PostgreSQL is an advanced, open-source relational database management system known for its reliability, performance, and extensive feature set.
  • It fully supports SQL standards and offers features such as JSONB data type for storing semistructured data, fulltext search capabilities, and support for advanced data types like arrays and ranges.
  • PostgreSQL is highly extensible, allowing users to define custom data types, functions, and indexing methods.
  • It also provides powerful transaction capabilities, ensuring data integrity and consistency.

Let’s Set Up an Environment

Before understanding the GraphQL APIs with PostgreSQL must ensure we have the following prerequisites:

  1. Node.js and npm: These are tools that help us to run JavaScript code on our computer. Node.js is the platform that runs JavaScript outside of web browsers, and npm is a package manager that help us to install and manage libraries and tools for our Node.js projects.
  2. PostgreSQL: This is a type of database software that stores data in a structured way, making it easy to retrieve and manipulate. It’s like a digital filing cabinet where we can store information for our applications.
  3. Basic knowledge of GraphQL and PostgreSQL concepts: Before we start, it’s helpful to have a basic understanding of what GraphQL and PostgreSQL are. GraphQL is a way to communicate with our database to retrieve and modify data, while PostgreSQL is the actual database where our data is stored.

Creating a GraphQL API with PostgreSQL

Let’s walk through the process of building a simple GraphQL API that interacts with a PostgreSQL database to manage a list of users.

Step 1: Set Up the Database Schema

Define the database schema to store user information, such as username, email, and age.

CREATE TABLE users (
  id SERIAL PRIMARY KEY,
  username VARCHAR(50) NOT NULL,
  email VARCHAR(100) NOT NULL,
  age INT
);

Explanation: This query creates a table named “users” with four columns: “id“, “username“, “email“, and “age“. The “id” column is defined as a SERIAL type, which automatically generates a unique value for each row. It is also designated as the PRIMARY KEY, meaning it uniquely identifies each row in the table.

The “username” and “email” columns are defined as VARCHAR types with maximum lengths of 50 and 100 characters, respectively, and are marked as NOT NULL, meaning they must have a value for each row. The “age” column is defined as an INT (integer) type. Overall, this query creates a basic table structure for storing user information.

Step 2: Initialize a Node.js Project

Create a new Node.js project and install necessary dependencies, including express, express-graphql, graphql, pg, and sequelize for PostgreSQL database interaction.

Step 3: Define GraphQL Schema

Define a GraphQL schema that specifies the data types and operations supported by the API, including queries to fetch users and mutations to create, update, and delete users.

type User {
  id: ID!
  username: String!
  email: String!
  age: Int
}


type Query {
  users: [User!]!
}


type Mutation {
  createUser(username: String!, email: String!, age: Int): User!
  updateUser(id: ID!, username: String, email: String, age: Int): User!
  deleteUser(id: ID!): User!
}

Explanation:

  1. User: Describes the structure of a user object with four fields:
    • id: An ID type that uniquely identifies a user (non-nullable).
    • username: A String type representing the user’s username (non-nullable).
    • email: A String type representing the user’s email address (non-nullable).
    • age: An Int type representing the user’s age.
  2. Query: Defines a single field users that returns a list of User objects (non-nullable). This field is used to fetch multiple users.
  3. Mutation: Defines three mutation operations (createUser, updateUser, deleteUser) to create, update, and delete users, respectively. Each mutation operation takes input arguments (username, email, age for createUser and updateUser; id for updateUser and deleteUser) and returns a User object (non-nullable).

Step 4: Implement Resolvers

Implement resolver functions to handle GraphQL queries and mutations, fetching and manipulating data from the PostgreSQL database using Sequelize ORM.

const { User } = require('./models');


const resolvers = {
  Query: {
    users: () => User.findAll(),
  },
  Mutation: {
    createUser: (_, args) => User.create(args),
    updateUser: (_, { id, ...args }) => {
      return User.update(args, { where: { id } }).then(() => User.findByPk(id));
    },
    deleteUser: (_, { id }) => {
      return User.findByPk(id).then(user => {
        return User.destroy({ where: { id } }).then(() => user);
      });
    },
  },
};

module.exports = resolvers;

Explanation:This JavaScript code defines resolver functions for GraphQL queries and mutations. Resolvers are responsible for fetching data for queries and executing actions for mutations.

  • The Query object contains a resolver for the users field. When the users field is queried, it resolves to a call to User.findAll(), which fetches all users from the database.
  • The Mutation object contains resolvers for three mutation operations: createUser, updateUser, and deleteUser. Each resolver takes input arguments and performs the corresponding action on the User model.
    • The createUser resolver creates a new user in the database using the input arguments.
    • The updateUser resolver updates an existing user in the database based on the provided id and input arguments.
    • The deleteUser resolver deletes an existing user from the database based on the provided id.

Step 5: Set Up GraphQL Server

Create an Express server and configure it to serve GraphQL API using express-graphql, providing the GraphQL schema and resolver functions.

Step 6: Run the Server

Start the Node.js server, and our GraphQL API backed by PostgreSQL is ready to use.

Conclusion

Building GraphQL APIs with PostgreSQL opens up a world of possibilities for developers, enabling them to create efficient and scalable backend systems that meet the demands of modern applications. By combining the flexibility of GraphQL with the reliability and performance of PostgreSQL, developers can deliver exceptional user experiences and unlock new opportunities for innovation and growth. As demonstrated in our example, the process of building GraphQL APIs with PostgreSQL is straightforward and accessible, making it a valuable skill for developers.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads