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
: AnID
type that uniquely identifies a user (non-nullable).username
: AString
type representing the user’s username (non-nullable).email
: AString
type representing the user’s email address (non-nullable).age
: AnInt
type representing the user’s age.
Query
: Defines a single fieldusers
that returns a list ofUser
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
forcreateUser
andupdateUser
;id
forupdateUser
anddeleteUser
) and returns aUser
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 theusers
field. When theusers
field is queried, it resolves to a call toUser.findAll()
, which fetches all users from the database. - The
Mutation
object contains resolvers for three mutation operations:createUser
,updateUser
, anddeleteUser
. Each resolver takes input arguments and performs the corresponding action on theUser
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 providedid
and input arguments. - The
deleteUser
resolver deletes an existing user from the database based on the providedid
.
- The
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.
Building GraphQL APIs with PostgreSQL
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.
Contact Us