🚀 GraphQL with NestJS: The Perfect Match for Scalable APIs!

GraphQL has revolutionized how we build APIs, offering a more flexible and efficient alternative to REST. When combined with NestJS, a powerful TypeScript framework, it provides a scalable, modular, and type-safe approach to backend development.
In this guide, we’ll explore how to integrate GraphQL with NestJS and build a simple API step by step.
🎯 Why Use GraphQL with NestJS?
✅ Strongly Typed API
GraphQL’s schema definition language (SDL) ensures type safety, reducing runtime errors.
✅ Efficient Data Fetching
Unlike REST, where you may over-fetch or under-fetch data, GraphQL allows clients to request only the necessary fields.
✅ Seamless NestJS Integration
NestJS provides built-in decorators for defining GraphQL resolvers, queries, and mutations, making implementation straightforward.
🚀 Setting Up a GraphQL API with NestJS
Let’s get started by creating a NestJS application with GraphQL support.
1️⃣ Install NestJS and Required Packages (choose npm)
npm i -g @nestjs/cli
nest new graphql-nestjs-app
cd graphql-nestjs-app
Next, install GraphQL dependencies:
npm i @nestjs/graphql @nestjs/apollo graphql apollo-server-express
2️⃣ Configure GraphQL Module
Modify app.module.ts
to set up the GraphQLModule:
import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';
import { join } from 'path';
import { UsersModule } from './users/users.module';
@Module({
imports: [
GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver,
autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
}),
UsersModule,
],
})
export class AppModule {}
3️⃣ Create a User Entity and DTO
Define a User entity inside users/user.model.ts
:
import { Field, ObjectType, Int } from '@nestjs/graphql';
@ObjectType()
export class User {
@Field(() => Int)
id: number;
@Field()
name: string;
@Field()
email: string;
}
4️⃣ Create a GraphQL Resolver
Create users/users.resolver.ts
:
import { Resolver, Query, Args, Int } from '@nestjs/graphql';
import { User } from './user.model';
import { UsersService } from './users.service';
@Resolver(() => User)
export class UsersResolver {
constructor(private readonly usersService: UsersService) {}
@Query(() => [User], { name: 'users' })
findAll(): User[] {
return this.usersService.findAll();
}
@Query(() => User, { name: 'user' })
findOne(@Args('id', { type: () => Int }) id: number): User {
return this.usersService.findOne(id);
}
}
5️⃣ Implement a Simple Service
Create users/users.service.ts
:
import { Injectable } from '@nestjs/common';
import { User } from './user.model';
@Injectable()
export class UsersService {
private users: User[] = [
{ id: 1, name: 'John Doe', email: 'john@example.com' },
{ id: 2, name: 'Jane Doe', email: 'jane@example.com' },
];
findAll(): User[] {
return this.users;
}
findOne(id: number): User {
return this.users.find(user => user.id === id);
}
}
6️⃣ Register the Resolver and Service
Modify users/users.module.ts
:
import { Module } from '@nestjs/common';
import { UsersResolver } from './users.resolver';
import { UsersService } from './users.service';
@Module({
providers: [UsersResolver, UsersService],
})
export class UsersModule {}
7️⃣ Start the Server and Test
Run the application:
npm run start:dev
Open http://localhost:3000/graphql and run the following query in GraphQL Playground:
query {
users {
id
name
email
}
}
🎉 Congratulations! You’ve successfully built a GraphQL API with NestJS.
🛠️ What’s Next?
Add mutations to create, update, and delete users.
Integrate with a database using Prisma or TypeORM.
Implement authentication and authorization.
Have you tried GraphQL with NestJS? Let’s discuss in the comments! 🚀
#GraphQL #NestJS #APIs #TypeScript #BackendDevelopment
Subscribe to my newsletter
Read articles from Leonardo de Almeida Teodoro directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
