DEV Community

Nadim Chowdhury
Nadim Chowdhury

Posted on • Edited on

How to Connect GraphQL API & Express JS backend with MySQL/PgSQL database?

Connecting a GraphQL API in an Express.js backend with a MySQL or PostgreSQL database involves several steps. Here’s a step-by-step guide for both databases:

Step 1: Set Up a New Express.js Project

  1. Initialize a New Project:
   mkdir project-name
   cd project-name
   npm init -y
Enter fullscreen mode Exit fullscreen mode
  1. Install Required Packages:
   npm install express express-graphql graphql
   npm install typeorm reflect-metadata mysql2 pg
   npm install type-graphql class-validator
Enter fullscreen mode Exit fullscreen mode

Step 2: Configure TypeORM

  1. Create a ormconfig.json File: For MySQL:
   {
     "type": "mysql",
     "host": "localhost",
     "port": 3306,
     "username": "root",
     "password": "password",
     "database": "test",
     "synchronize": true,
     "logging": false,
     "entities": [
       "src/entity/**/*.ts"
     ]
   }
Enter fullscreen mode Exit fullscreen mode

For PostgreSQL:

   {
     "type": "postgres",
     "host": "localhost",
     "port": 5432,
     "username": "user",
     "password": "password",
     "database": "test",
     "synchronize": true,
     "logging": false,
     "entities": [
       "src/entity/**/*.ts"
     ]
   }
Enter fullscreen mode Exit fullscreen mode

Step 3: Define the User Entity

  1. Create a Directory Structure:
   mkdir -p src/entity src/resolvers
Enter fullscreen mode Exit fullscreen mode
  1. Create the User Entity: Create src/entity/User.ts:
   import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
   import { ObjectType, Field, ID } from 'type-graphql';

   @ObjectType()
   @Entity()
   export class User {
     @Field(() => ID)
     @PrimaryGeneratedColumn()
     id: number;

     @Field()
     @Column()
     name: string;

     @Field()
     @Column()
     email: string;
   }
Enter fullscreen mode Exit fullscreen mode

Step 4: Create the User Resolver

  1. Create the User Resolver: Create src/resolvers/UserResolver.ts:
   import { Resolver, Query, Mutation, Arg } from 'type-graphql';
   import { User } from '../entity/User';
   import { getRepository } from 'typeorm';

   @Resolver()
   export class UserResolver {
     private userRepository = getRepository(User);

     @Query(() => [User])
     async users() {
       return this.userRepository.find();
     }

     @Mutation(() => User)
     async createUser(@Arg('name') name: string, @Arg('email') email: string) {
       const user = this.userRepository.create({ name, email });
       return this.userRepository.save(user);
     }
   }
Enter fullscreen mode Exit fullscreen mode

Step 5: Set Up the Express.js Server

  1. Create the Server: Create src/index.ts:
   import 'reflect-metadata';
   import { createConnection } from 'typeorm';
   import express from 'express';
   import { graphqlHTTP } from 'express-graphql';
   import { buildSchema } from 'type-graphql';
   import { UserResolver } from './resolvers/UserResolver';

   async function bootstrap() {
     await createConnection();

     const schema = await buildSchema({
       resolvers: [UserResolver],
     });

     const app = express();

     app.use(
       '/graphql',
       graphqlHTTP({
         schema,
         graphiql: true,
       }),
     );

     app.listen(4000, () => {
       console.log('Server is running on http://localhost:4000/graphql');
     });
   }

   bootstrap();
Enter fullscreen mode Exit fullscreen mode

Step 6: Compile TypeScript and Run the Server

  1. Install TypeScript and ts-node:
   npm install typescript ts-node @types/node @types/express
Enter fullscreen mode Exit fullscreen mode
  1. Add TypeScript Configuration: Create tsconfig.json:
   {
     "compilerOptions": {
       "target": "ES6",
       "module": "commonjs",
       "strict": true,
       "esModuleInterop": true,
       "skipLibCheck": true,
       "outDir": "./dist"
     },
     "include": ["src"]
   }
Enter fullscreen mode Exit fullscreen mode
  1. Compile and Run the Server:
   npx ts-node src/index.ts
Enter fullscreen mode Exit fullscreen mode

Step 7: Test the GraphQL API

  1. Access the GraphQL Playground: Navigate to http://localhost:4000/graphql to access the GraphQL playground and test your API by running queries and mutations.

Example GraphQL Queries and Mutations

  • Query All Users:
  {
    users {
      id
      name
      email
    }
  }
Enter fullscreen mode Exit fullscreen mode
  • Create a New User:
  mutation {
    createUser(name: "John Doe", email: "john.doe@example.com") {
      id
      name
      email
    }
  }
Enter fullscreen mode Exit fullscreen mode

This guide provides a foundational approach to creating a GraphQL API in an Express.js backend connected to a MySQL or PostgreSQL database. You can further expand and customize it based on your application's requirements.

Support My Work ❤️

If you enjoy my content and find it valuable, consider supporting me by buying me a coffee. Your support helps me continue creating and sharing useful resources. Thank you!

Connect with Me 🌍

Let’s stay connected! You can follow me or reach out on these platforms:

🔹 YouTube – Tutorials, insights & tech content

🔹 LinkedIn – Professional updates & networking

🔹 GitHub – My open-source projects & contributions

🔹 Instagram – Behind-the-scenes & personal updates

🔹 X (formerly Twitter) – Quick thoughts & tech discussions

I’d love to hear from you—whether it’s feedback, collaboration ideas, or just a friendly hello!

Disclaimer

This content has been generated with the assistance of AI. While I strive for accuracy and quality, please verify critical information independently.

Heroku

Deliver your unique apps, your own way.

Heroku tackles the toil — patching and upgrading, 24/7 ops and security, build systems, failovers, and more. Stay focused on building great data-driven applications.

Learn More

Top comments (0)

Image of Stellar post

🚀 Stellar Dev Diaries Series: Episode 1 is LIVE!

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay