setting-up-a-graphql-api-with-expressjs-and-prisma-orm.html

Setting Up a GraphQL API with Express.js and Prisma ORM

In the world of web development, building robust APIs is a critical component of modern applications. With the advent of GraphQL, developers have embraced a more flexible and efficient way to interact with data. In this article, we'll dive into setting up a GraphQL API using Express.js and Prisma ORM. By the end, you’ll have a fully functional API that demonstrates key concepts and coding practices.

What is GraphQL?

GraphQL is a query language for your API, offering a more efficient and powerful alternative to REST. It allows clients to request only the data they need, minimizing the amount of data transferred over the network. GraphQL provides a single endpoint for your API, making it easier to manage and scale.

Why Use Express.js?

Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for building web and mobile applications. Its simplicity and performance make it an excellent choice for setting up a GraphQL server. With Express.js, you can quickly create RESTful APIs and integrate GraphQL seamlessly.

Enter Prisma ORM

Prisma is a modern Object-Relational Mapping (ORM) tool that simplifies database interactions. It provides a type-safe and easy-to-use API for querying your database and managing schema migrations. Using Prisma with GraphQL allows you to focus on your application logic rather than on raw SQL queries.

Prerequisites

Before we get started, ensure you have the following installed on your machine:

  • Node.js (version 12 or later)
  • npm or yarn
  • A database (e.g., PostgreSQL, MySQL, SQLite)

Step 1: Setting Up the Project

First, create a new directory for your project and initialize it with npm:

mkdir graphql-express-prisma
cd graphql-express-prisma
npm init -y

Next, install the required dependencies:

npm install express graphql express-graphql prisma @prisma/client

Step 1.1: Initialize Prisma

Run the following command to set up Prisma in your project:

npx prisma init

This command creates a new prisma directory with a schema.prisma file. You will define your data models in this file.

Step 2: Define Your Data Model

Open the schema.prisma file and define your data model. For this example, let’s create a simple model for a blog:

datasource db {
  provider = "sqlite" // Use SQLite for simplicity
  url      = "file:./dev.db"
}

generator client {
  provider = "prisma-client-js"
}

model Post {
  id      Int     @id @default(autoincrement())
  title   String
  content String
}

Step 2.1: Migrate the Database

Now, we need to create the database and apply the migration:

npx prisma migrate dev --name init

This command will create a SQLite database file (dev.db) and apply the initial migration based on your Prisma schema.

Step 3: Create the GraphQL Schema

Next, create a new file named schema.js in your project root. This will define your GraphQL types and resolvers:

const { GraphQLObjectType, GraphQLString, GraphQLSchema, GraphQLList } = require('graphql');
const { PrismaClient } = require('@prisma/client');

const prisma = new PrismaClient();

// Define the Post type
const PostType = new GraphQLObjectType({
  name: 'Post',
  fields: () => ({
    id: { type: GraphQLString },
    title: { type: GraphQLString },
    content: { type: GraphQLString },
  }),
});

// Root Query to get all posts
const RootQuery = new GraphQLObjectType({
  name: 'RootQueryType',
  fields: {
    posts: {
      type: new GraphQLList(PostType),
      resolve(parent, args) {
        return prisma.post.findMany();
      },
    },
  },
});

// Mutation to create a post
const Mutation = new GraphQLObjectType({
  name: 'Mutation',
  fields: {
    addPost: {
      type: PostType,
      args: {
        title: { type: GraphQLString },
        content: { type: GraphQLString },
      },
      resolve(parent, args) {
        return prisma.post.create({
          data: {
            title: args.title,
            content: args.content,
          },
        });
      },
    },
  },
});

module.exports = new GraphQLSchema({
  query: RootQuery,
  mutation: Mutation,
});

Step 4: Set Up Express and GraphQL Server

Now that we have our GraphQL schema defined, we can set up our Express server. Create a new file called server.js:

const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const schema = require('./schema');

const app = express();
const PORT = process.env.PORT || 4000;

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

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

Step 5: Running the Application

To start your application, run:

node server.js

Now, navigate to http://localhost:4000/graphql in your browser. You can use the GraphiQL interface to test your GraphQL queries. For example, you can retrieve all posts with the following query:

{
  posts {
    id
    title
    content
  }
}

Add a Post

To add a new post, you can use the following mutation:

mutation {
  addPost(title: "My First Post", content: "This is the content of my first post.") {
    id
    title
    content
  }
}

Troubleshooting Common Issues

  • Database Connection Errors: Ensure your database is running and your connection string in schema.prisma is correct.
  • Schema Not Updated: If you change your Prisma schema, remember to run npx prisma migrate dev to apply migrations.
  • GraphQL Errors: Double-check your GraphQL queries and mutations for typos or incorrect field names.

Conclusion

In this article, we have successfully set up a GraphQL API using Express.js and Prisma ORM. You now have a solid foundation to build upon. By leveraging the flexibility of GraphQL and the power of Prisma, you can create efficient and scalable APIs that enhance your applications. Happy coding!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.