Building GraphQL APIs with PostgreSQL
Last Updated :
19 Mar, 2024
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 semi-structured data, full-text 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:
- 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.
- 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.
- 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:
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.
Query
: Defines a single field users
that returns a list of User
objects (non-nullable). This field is used to fetch multiple users.
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.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
DBMS Tutorial â Learn Database Management System Database Management System (DBMS) is a software used to manage data from a database. A database is a structured collection of data that is stored in an electronic device. The data can be text, video, image or any other format.A relational database stores data in the form of tables and a NoSQL databa
7 min read
Introduction of ER Model The Entity-Relationship Model (ER Model) is a conceptual model for designing a databases. This model represents the logical structure of a database, including entities, their attributes and relationships between them. Entity: An objects that is stored as data such as Student, Course or Company.Attri
10 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Normal Forms in DBMS In the world of database management, Normal Forms are important for ensuring that data is structured logically, reducing redundancy, and maintaining data integrity. When working with databases, especially relational databases, it is critical to follow normalization techniques that help to eliminate
7 min read
ACID Properties in DBMS In the world of DBMS, transactions are fundamental operations that allow us to modify and retrieve data. However, to ensure the integrity of a database, it is important that these transactions are executed in a way that maintains consistency, correctness, and reliability. This is where the ACID prop
8 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Introduction of DBMS (Database Management System) A Database Management System (DBMS) is a software solution designed to efficiently manage, organize, and retrieve data in a structured manner. It serves as a critical component in modern computing, enabling organizations to store, manipulate, and secure their data effectively. From small application
8 min read
SQL Query Interview Questions SQL or Structured Query Language, is the standard language for managing and manipulating relational databases such as MySQL, Oracle, and PostgreSQL. It serves as a powerful tool for efficiently handling data whether retrieving specific data points, performing complex analysis, or modifying database
15+ min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read