# Beginner's Guide to Using GraphQL with NestJS

[GraphQL](https://blog.bytescrum.com/how-to-create-a-graphql-server-with-nestjs-and-typescript) is a powerful query language for APIs that allows clients to request exactly the data they need. [NestJS](https://bytescrum.com/), a progressive Node.js framework, provides excellent support for building GraphQL APIs. In this guide, we'll explore how to get started with GraphQL in NestJS, covering the essential steps from setting up your project to creating resolvers and defining schemas.

## Why Choose GraphQL with NestJS?

1. **Efficient Data Fetching:** GraphQL allows clients to request only the data they need, reducing over-fetching and under-fetching.
    
2. **Strongly Typed Schema:** The GraphQL schema provides a clear contract for your API, ensuring type safety and better developer experience.
    
3. **NestJS Integration:** NestJS seamlessly integrates with GraphQL, providing decorators, modules, and tools to simplify development.
    

## Setting Up a NestJS Project with GraphQL

### Step 1: Install NestJS CLI

First, install the [NestJS](https://blog.bytescrum.com/introduction-to-nestjs-a-beginners-guide) Command Line Interface (CLI):

```bash
npm install -g @nestjs/cli
```

### Step 2: Create a New Project

Create a new NestJS project using the CLI:

```bash
nest new my-graphql-api
```

Navigate into your project directory:

```bash
cd my-graphql-api
```

### Step 3: Install GraphQL Dependencies

Install the necessary GraphQL dependencies:

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

### Step 4: Configure GraphQL Module

Open the `src/app.module.ts` file and configure the GraphQL module:

```typescript
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 {}
```

## Creating Your First Module, Resolver, and Schema

### Step 1: Generate a Module

Generate a new module for users:

```bash
nest generate module users
```

### Step 2: Generate a Resolver and Service

Generate a resolver and a service for the `users` module:

```bash
nest generate resolver users
nest generate service users
```

### Step 3: Define User Type

Create a GraphQL type for the user entity in `src/users/user.type.ts`:

```typescript
import { Field, ObjectType, Int } from '@nestjs/graphql';

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

  @Field()
  name: string;

  @Field()
  email: string;
}
```

### Step 4: Implement the Users Service

Open the `src/users/users.service.ts` file and implement the service methods:

```typescript
import { Injectable } from '@nestjs/common';
import { User } from './user.type';

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

  findAll(): User[] {
    return this.users;
  }

  findOne(id: number): User {
    return this.users.find(user => user.id === id);
  }
}
```

### Step 5: Implement the Users Resolver

Open the `src/users/users.resolver.ts` file and implement the resolver methods:

```typescript
import { Resolver, Query, Args, Int } from '@nestjs/graphql';
import { UsersService } from './users.service';
import { User } from './user.type';

@Resolver(of => User)
export class UsersResolver {
  constructor(private usersService: UsersService) {}

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

  @Query(returns => User)
  user(@Args('id', { type: () => Int }) id: number): User {
    return this.usersService.findOne(id);
  }
}
```

### Step 6: Testing Your GraphQL API

Run the application:

```bash
npm run start
```

By default, the application runs on [`http://localhost:3000`](http://localhost:3000). Navigate to [`http://localhost:3000/graphql`](http://localhost:3000/graphql) to access the GraphQL Playground, where you can test your API.

Example queries:

* **Fetch all users:**
    
    ```graphql
    {
      users {
        id
        name
        email
      }
    }
    ```
    
* **Fetch a user by ID:**
    
    ```graphql
    {
      user(id: 1) {
        id
        name
        email
      }
    }
    ```
    

> "GraphQL is a powerful query language that enables clients to request exactly the data they need, making APIs more efficient and flexible."

<details data-node-type="hn-details-summary"><summary>Conclusion</summary><div data-type="detailsContent">NestJS provides robust support for building GraphQL APIs, offering a seamless integration that leverages the framework's modular architecture and TypeScript features. This guide covered the basics of setting up a NestJS project with GraphQL, creating modules, resolvers, and defining schemas. With this foundation, you are well-equipped to build efficient and scalable GraphQL APIs using NestJS.</div></details>
