4-building-a-graphql-api-with-nestjs-and-typescript.html

Building a GraphQL API with NestJS and TypeScript

In today's fast-paced development environment, creating efficient APIs is crucial for powering modern applications. GraphQL, a query language for your API, allows clients to request only the data they need, which can lead to improved performance and a better developer experience. Combined with NestJS, a progressive Node.js framework, and TypeScript, a strongly typed language built on JavaScript, you can build robust and type-safe APIs. In this article, we will walk through the process of building a GraphQL API using NestJS and TypeScript, providing you with insightful code examples and actionable steps.

What is GraphQL?

GraphQL is an open-source data query language developed by Facebook. Unlike traditional REST APIs that expose multiple endpoints for different resources, GraphQL provides a single endpoint that can handle various queries. This allows clients to specify exactly what data they need, reducing over-fetching and under-fetching of data.

Key Features of GraphQL:

  • Single Endpoint: All requests are made to one endpoint.
  • Strongly Typed Schema: GraphQL APIs are defined by a schema, which allows for better validation and introspection.
  • Client-Specified Queries: Clients can request only the fields they need, optimizing data transfer.

What is NestJS?

NestJS is a framework for building efficient and scalable server-side applications using Node.js. It leverages TypeScript's features to provide a modular architecture, making it easy to maintain and test your applications. NestJS supports various transport layers, including HTTP and WebSockets, and can be extended with other libraries.

Benefits of Using NestJS:

  • Modular Structure: Encourages code organization and reusability.
  • Built-in Support for GraphQL: Makes it easy to set up a GraphQL server.
  • Dependency Injection: Simplifies the management of service instances.

Getting Started with NestJS and GraphQL

Prerequisites

Before we dive into the code, ensure you have the following installed:

  • Node.js (version 12 or later)
  • npm (Node Package Manager)
  • TypeScript (optional but recommended)

Step 1: Setting Up Your NestJS Project

First, create a new NestJS project using the Nest CLI. If you don't have the Nest CLI installed, you can do so with the following command:

npm i -g @nestjs/cli

Now, create a new project:

nest new graphql-nestjs

Navigate into your project directory:

cd graphql-nestjs

Step 2: Installing Required Packages

To add GraphQL support to your NestJS application, install the necessary dependencies:

npm install @nestjs/graphql graphql apollo-server-express

You will also need to install the TypeScript types for Node.js and GraphQL:

npm install @types/node @types/graphql --save-dev

Step 3: Configuring GraphQL in NestJS

Open the app.module.ts file and import the GraphQLModule. You will need to configure it to use ApolloServer.

import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [
    GraphQLModule.forRoot({
      autoSchemaFile: true, // Automatically generate schema file
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Step 4: Creating Your First GraphQL Schema

NestJS utilizes decorators to define your GraphQL schema. Let's create a simple User entity first.

  1. Create a new directory called users.
  2. Inside the users directory, create a file named user.model.ts.
import { ObjectType, Field, Int } from '@nestjs/graphql';

@ObjectType()
export class User {
  @Field(() => Int)
  id: number;

  @Field()
  name: string;

  @Field()
  email: string;
}

Step 5: Creating a Resolver

Next, create a resolver to handle fetching user data. Create a file named users.resolver.ts in the users directory:

import { Resolver, Query } from '@nestjs/graphql';
import { User } from './user.model';

@Resolver(() => User)
export class UsersResolver {
  private readonly users: User[] = [
    { id: 1, name: 'John Doe', email: 'john@example.com' },
    { id: 2, name: 'Jane Doe', email: 'jane@example.com' },
  ];

  @Query(() => [User])
  getUsers(): User[] {
    return this.users;
  }
}

Step 6: Registering the Resolver

You must register your resolver in the module. Open app.module.ts and update it as follows:

import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { UsersResolver } from './users/users.resolver';

@Module({
  imports: [
    GraphQLModule.forRoot({
      autoSchemaFile: true,
    }),
  ],
  providers: [UsersResolver],
})
export class AppModule {}

Step 7: Running Your Application

Now that you have set everything up, run your NestJS application:

npm run start:dev

Navigate to http://localhost:3000/graphql to access the GraphQL Playground. Here, you can test your getUsers query:

query {
  getUsers {
    id
    name
    email
  }
}

Conclusion

Building a GraphQL API with NestJS and TypeScript provides a powerful way to create scalable and type-safe applications. By following the steps outlined in this article, you have set up a basic GraphQL server that can be extended to include more complex logic, additional entities, and advanced features.

As you continue your journey with NestJS and GraphQL, consider exploring topics such as authentication, real-time data with subscriptions, and integrating with databases for persistent storage. 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.