How to Build a Node.js GraphQL API With NestJS and Prisma

Yuval Hazaz - Jul 6 '23 - - Dev Community

Are you interested in building highly scalable and performant server-side applications? Have you considered using Node.js, a widely used and robust runtime environment? Recently, developers have preferred using GraphQL with Node.js to build faster and more flexible APIs than the more traditional REST APIs.

To fully leverage the potential of GraphQL, it is essential to have a reliable framework that can handle the complexities of a growing codebase and an Object Relational Mapping (ORM) tool that simplifies database interactions. NestJS and Prisma are a great couple that can provide exactly that. NestJS is a powerful framework specifically designed for building Node.js applications, while Prisma is an ORM tool that provides a type-safe API for querying databases in Node.js.

This article aims to provide insights on building a Node.js GraphQL API using NestJS and Prisma while addressing some of the most frequently asked questions about these technologies.

Many of you are likely well-versed in creating traditional Node.js applications. However, this article will present a unique approach to building a Node.js GraphQL API with NestJS and Prisma, utilizing the Amplication platform to simplify the development process further. But before getting into action, let's get familiar with the technologies mentioned above.

GraphQL

GraphQL is an open-source query language that provides a more efficient and flexible way to request and manipulate server data. In REST APIs, users must send multiple requests to different endpoints to retrieve various data. In contrast, GraphQL allows users to construct queries that define the exact shape and structure of the data they require, eliminating the over-fetching and under-fetching of data.

Prisma

Prisma is an open-source database toolkit and ORM that provides tools and features to simplify database access in your applications. It abstracts the database-specific details, allowing developers to work with multiple database systems (such as PostgreSQL, MySQL, SQLite, and SQL Server) without writing specific code for each database.

NestJS

NestJS is an open-source framework for building efficient, scalable, and maintainable server-side applications using TypeScript. Angular inspires NestJS and uses TypeScript features like strong typing, decorators, and dependency injection to provide a robust architecture for building server-side applications.

Amplication

Amplication is an open-source platform that automatically generates APIs and clients based on pre-defined data models. It streamlines the development process by minimizing repetitive coding tasks and boilerplate code, enabling developers to focus on building backend services more efficiently.

In this article, I will combine the power of Amplication, Prisma, GraphQL, and NestJS to create a simple Node.js service with three entities to manage my Blogs.

The Steps

Step 1 - Create a New Project in Amplication

Once you log in to the Amplication dashboard, you will see an option to create a New project in the bottom left corner. It will open a modal to enter a project name and click the Create new Project button.

Step 2 - Create a New Service

Then, click the Add Resource button and select the Service option from the dropdown.

It will redirect you to a new wizard to configure the new service. First, you need to enter a name for the service.

Then, connect to a GitHub repository where you want to get the generated code.

Next, you need to choose between GraphQL and REST. Since this article is about GraphQL, I have only enabled GraphQL API and Admin UI options.

Next, you can select between Monorepo and Polyrepo based on your project and team requirements. For this example, you can leave the default settings as it is.

Next, you must select between PostgreSQL, MongoDB, and MySQL for database options.

Also, Amplication can automatically generate entities for your database models if you prefer. We will define the data model for our use case later, so select "Empty."

Finally, you can include authentication for your service. If you opt to have the auth module, Amplication will automatically generate the authentication code for your service.

Once the service is created, you will see a window like the one below. Click on Create entities for my service option to start creating entities for the new service.

Step 3 - Create Entities

By default, Amplication creates a user entity to manage users related to your service. You can easily create new entities by clicking the Add Entity button in the Entities tab.

First, you need to enter the entity name.

Then, you will get a window like the one below where you can create fields for the entity. For each field, you can configure properties like uniqueness, required or not, searchability, data type, max length, etc.

After creating the models, you can access the Amplication UI and review them to ensure they have been generated correctly per your expectations. As explained earlier, I have created three entities for my BlogService: Blog, Publication, and Author.

Step 4: Commit Changes

Once all the entities are created, click the Commit changes & build button to sync the changes with the GitHub repository.

Step 5: Get the Source Code

Now you can navigate to the GitHub repo by clicking the Open With GitHub button and clone the source code to your local machine.

That concludes the process. Amplication has successfully generated all the required files and boilerplate code for you. For example, the amplication-example/apps/blog-service/src/blog/base folder contains the Blog model, DTOs, GraphQL resolver, Service, and tests.

Now you can open the code with VSCode, and customize it.

Step 6: Install npm Packages

Once the application is ready, you must install npm packages and dependencies using the npm install command.

Step 7: Start the Docker Container for the Database

Start the Docker container to run the database using the below command.

npm run docker:db
Enter fullscreen mode Exit fullscreen mode

Then create the application schema on the database using Prisma. You can use the below migration commands for that:

npm run prisma:generate 
npm run db:init
Enter fullscreen mode Exit fullscreen mode

Step 8: Run the Application

Finally, you can run the application using the npm run start command. It will start the server at http://localhost:3000.

Also, you can access the GraphQL server through http://localhost:3000/graphql.

Fun Fact

One fascinating fact about the Amplication blog is that its backend is built entirely using Amplication itself. By utilizing Amplication for our own blog, we are not only showcasing its potential but also benefiting from its efficiency and productivity-enhancing features. It's worth mentioning that the entire codebase of the Amplication blog's backend is publicly available on GitHub, allowing developers to explore, learn, and contribute to its development. You can find the code repository for the blog server at https://github.com/amplication/blog-server. We believe in transparency and collaboration, and making the code available underscores our commitment to fostering an open-source community. Feel free to delve into the codebase and witness firsthand how Amplication powers the backend of our blog.

Conclusion

In summary, Amplication dramatically simplifies generating GraphQL APIs using Nest.JS and Prisma. With just a few steps, developers can quickly generate all the necessary files for multiple data models.

Amplication is a free, open-source tool that accelerates development by creating fully functional Node.js services. In addition to Nest.js and Prisma, it supports several other technologies such as PostgreSQL, MySQL, MongoDB, Passport, Jest, and Docker. Therefore, I encourage you to try Amplication and experience the difference it can make in your development workflow.

FAQs

Q1: What is Prisma?

Prisma is a widely recognized ORM (Object-Relational Mapping) tool that smoothly integrates with NestJS. Using Prisma, developers can easily create database schemas with a simple syntax and construct type-safe APIs for querying databases. Additionally, Prisma facilitates writing database queries and resolving database-related errors in NestJS applications, making it an efficient tool for developers.

Q2: Does NestJS use GraphQL?

Indeed, NestJS has built-in support for GraphQL. It provides two methods for constructing applications with GraphQL: code-first and schema-first. The code-first approach employs decorators and TypeScript classes to produce a GraphQL schema, whereas the schema-first approach utilizes GraphQL SDL (Schema Definition Language).

Q3: How Is GraphQL Different From REST?

GraphQL and REST are 2 of the most popular approaches in building APIs. However, there are some significant differences between them. You can find a detailed comparison between GraphQL and REST here.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .